【问题标题】:Entity Framework many to many incorrect table mapping实体框架多对多不正确的表映射
【发布时间】:2017-05-18 10:16:50
【问题描述】:

我正在尝试使这种多对可能的关系正常工作,这是架构

我的实体有以下配置,第一个 ContentBranch 实体:

configuration.HasMany(e => e.ContentLeafs)
            .WithMany(e => e.ContentBranches)
            .Map(m => m.MapLeftKey("ContentLeafId").MapRightKey("ContentBranchId").ToTable("ContentBranchLeafs"));

然后是 ContentLeaf 实体:

 configuration.HasMany(e => e.ContentBranches)
            .WithMany(e => e.ContentLeafs)
            .Map(e => e.MapLeftKey("ContentBranchId").MapRightKey("ContentLeafId").ToTable("ContentBranchLeafs"));

我正在尝试执行以下测试代码:

 theBranch.ContentLeafs.Add(theLeaf);
            await contentBranchRepository.Update(theBranch);

问题出在映射上,因为我得到了以下异常:

保存不为其关系公开外键属性的实体时发生错误。 EntityEntries 属性将返回 null,因为无法将单个实体标识为异常源。通过在实体类型中公开外键属性,可以更轻松地在保存时处理异常。有关详细信息,请参阅 InnerException。

内部异常:

无效的对象名称“dbo.ContentLeafContentBranches”。

有谁知道为什么 EF 在我提供显式表名时使用约定?请帮忙。

【问题讨论】:

  • 我的代码中有这个并且它正在工作 HasMany(s => s.ContentLeafs) .WithMany(c => c.ContentBranches) .Map(cs => { cs.MapLeftKey("ContentBranchId "); cs.MapRightKey("ContentLeafId"); cs.ToTable("ContentBranchLeafs"); });

标签: c# entity-framework


【解决方案1】:

尝试在您的实体配置中切换映射键,即:为 ContentLeafs 切换 MapLeftKey 和 MapRightKey,您可以对 Content 分支执行相同操作。这为我解决了你的问题。

【讨论】:

  • 感谢您的回答,但我已经尝试过了,仍然遇到同样的异常
【解决方案2】:

在 Fluent Api 中,您只需设置一侧。

现在只用这个试试

 configuration.HasMany(e => e.ContentLeafs)
            .WithMany(e => e.ContentBranches)
            .Map(m => m.MapLeftKey("ContentLeafId").MapRightKey("ContentBranchId").ToTable("ContentBranchLeafs"));

【讨论】:

  • 谢谢你的想法,试过但它一定是我错过的其他东西,仍然是同样的例外
【解决方案3】:

这是我的错。我负责自动注册类型配置的代码有一些问题,以上两个答案都是正确的。

【讨论】:

    猜你喜欢
    • 2017-12-04
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    相关资源
    最近更新 更多