【问题标题】:EF Code First Fluent API specifying the Foreign Key propertyEF Code First Fluent API 指定外键属性
【发布时间】:2013-10-21 23:33:29
【问题描述】:

我有一个与 Agent 关联的类 AgentBalance,因此:

public class AgentBalance
{
    ...

    public int AgentId { get; set; }

    public virtual Agent Agent { get; set; }

}

按照惯例,AgentId 被检测为代理关系的 FK,但我想在 Mapping 类中明确表示它,以便更安全地应对未来的变化。如果代理有一组余额,那么我知道如何执行此操作,例如:

HasRequired(t => t.Agent).WithMany(a => a.Balances).HasForeignKey(t => t.AgentId);

但是,代理 没有 有余额集合 - 我不希望该关联可以反向导航。但是如果没有映射中的 .WithMany,我将无法选择指定 .HasForeignKey。还有其他方法吗? (注意,我知道我也可以使用属性来做到这一点,但我想使用流畅的 API 映射)。

【问题讨论】:

    标签: entity-framework ef-code-first


    【解决方案1】:

    我相信你应该能够做到这一点:

    HasRequired(t => t.Agent).WithMany().HasForeignKey(t => t.AgentId)
    

    【讨论】:

    • 谢谢 - 我错过了 WithMany() 超载!不过,这似乎是一种奇怪的语法。我不明白他们为什么不能让你写这样的东西: HasRequired(t => t.Agent).HasForeignKey(t => t.AgentId)
    • EF 没有办法知道它是什么类型的关系。
    • 这对我不起作用。除了我已明确配置为外键列的 AgentId 之外,EF 还会创建一个新的 Agent_Id 列。你知道为什么会这样吗?
    • 同样,我发现每当我尝试显式设置外键时,显式迁移脚本就完全搞砸了,疯了...
    • @Yukian @red2nb 这可能是因为当您在另一个实体上拥有集合时,您需要在 WithMany() 中指定适当的映射。例如,.WithMany(agent => agent.Balances)
    【解决方案2】:

    我更喜欢对这些任务使用数据注释,而不是 Fluent API。它的长度要短得多,易于理解。 EF 必须自动检测以“Id”结尾的属性,但为了安全起见,您可以明确指定它们:

    using System.ComponentModel.DataAnnotations.Schema;
    ...
    public int AgentId { get; set; }
    
    [ForeignKey("AgentId")]
    public virtual Agent Agent { get; set; }
    

    如果您的 FK 道具不以“Id”结尾,则需要明确指定它们,例如:

    public int AgentCode { get; set; }
    
    [ForeignKey("AgentCode")] // now this is needed if you'd like to have FK created
    public virtual Agent Agent { get; set; }
    

    您可以在此处找到更多详细信息:https://msdn.microsoft.com/en-us/data/jj591583.aspx

    【讨论】:

    • 数据注释,我同意,更容易阅读。但这不是 IMO 管理大型复杂项目的好方法,这是我的背景。
    • @RichardPawson 为什么不呢?
    • @gsharp 这是因为 DataAnnotations 不如 Fluent API 强大,所以在大型项目中,您总是需要使用 Fluent API,因为 DataAnnotations 不够用,当这种情况发生时,您最终会得到配置在两个地方,最好将模型的所有配置都放在一个地方。
    • @SOfanatic 同时我同意你的看法。 Iv'e 从数据注释的新手开始,很快就切换到 Fluent API。但是我更喜欢从 EntityTypeConfiguration 继承并且每个实体都有一个配置。
    • @gsharp 是的,这是正确的方法,您甚至可能想为 EntityTypeConfiguration 创建自己的“基”类,这样您就可以在数据库初始化时自动注册配置
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 2014-01-20
    • 2013-03-02
    • 2014-09-26
    • 1970-01-01
    相关资源
    最近更新 更多