EF 4.1生成字段[Name]_Id而不是[Name]Id,FK相关问题

发布于 2024-11-17 13:36:25 字数 928 浏览 0 评论 0原文

我有这样的类:


public class Target
{
    [Key]
    [Column("TargetId")]
    public Guid Id { get; set; }

    [ForeignKey("TargetInventory")]
    public Guid? TargetInventoryId { get; set; }
    public virtual TargetInventory TargetInventory { get; set; }
}

在 DbContext 上只有这个:


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove();
}

在数据库上我有名为“FK_Target_TargetInventory”的 FK 和字段“TargetInventoryId”。

在 EF 4 中它可以工作,但在 4.1 上它会生成无效的字段名称“TargetInventory_Id”而不是“TargetInventoryId”。例外:

查询“GetAll”的加载操作失败。执行命令定义时出错。有关详细信息,请参阅内部异常。内部异常消息:列名“TargetInventory_Id”无效。

可能出什么问题了?

编辑1

代码标签渲染得不好(我想你能明白它的意思): modelBuilder.Conventions.Remove<<'IncludeMetadataConvention'>>(); 我以前没有使用过 Fluent 并且它有效,我不想在主类之外有逻辑。 现在我将尝试各种测试,因为我发现类似的代码在不同的类中工作。

I have class like this:


public class Target
{
    [Key]
    [Column("TargetId")]
    public Guid Id { get; set; }

    [ForeignKey("TargetInventory")]
    public Guid? TargetInventoryId { get; set; }
    public virtual TargetInventory TargetInventory { get; set; }
}

On DbContext only this:


protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove();
}

On database I have FK named 'FK_Target_TargetInventory' and field 'TargetInventoryId'.

With EF 4 it worked but on 4.1 it generates invalid field name 'TargetInventory_Id' instead of 'TargetInventoryId'. Exception:

Load operation failed for query 'GetAll'. An error occurred while executing the command definition. See the inner exception for details. Inner exception message: Invalid column name 'TargetInventory_Id'.

What could be wrong?

Edit 1

Code tag is not rendering well (I think you can understand what it means):
modelBuilder.Conventions.Remove<<'IncludeMetadataConvention'>>();
I havent used fluent before and it worked, I don't want to have logic outside main class.
Now I will try various tests as I found similiar code working in different class.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

木有鱼丸 2024-11-24 13:36:25

您要删除什么约定?不要触碰惯例。它们负责 FK 属性与导航属性的自动配对,还负责将数据注释转换为映射。如果您的代码意味着您要删除所有约定,则必须使用流畅的 API 配置所有内容。

What convention are you removing? Don't touch conventions. They are responsible for automatic pairing of FK property with navigation property and they are also responsible for converting data annotations to mapping. If your code should mean that you are removing all conventions you must configure everything with fluent API.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文