【问题标题】:Specifying HasForeignKey with ModelBuilder?使用模型构建器指定 HasForeignKey?
【发布时间】:2013-11-24 02:01:49
【问题描述】:

假设我有一个“关系”实体:

public class Relationship
{
    [Key]
    [Required]
    public int RelationshipId { get; set; }

    [Required]
    public int FriendOneId { get; set; }
    public virtual User FriendOne{ get; set; }

    [Required]
    public int FriendTwoId { get; set; }
    public virtual User FriendTwo { get; set; }
}

如果我想用模型构建器映射这些关系,这有什么区别:

        modelBuilder.Entity<Relationship>()
        .HasRequired(c => c.FriendOne)
        .WithMany()
        .HasForeignKey(u => u.FriendOneId);

还有这个:

       modelBuilder.Entity<Relationship>()
        .HasRequired(c => c.FriendOne)
        .WithMany()
        .HasForeignKey(u => u.RelationshipId);

每次设置新数据库时,我都会对此感到困惑。我找到的文档和关于 SO 的答案似乎在这方面相互冲突......在理解如何使用 HasForeignKey 方面的任何帮助将不胜感激。

【问题讨论】:

    标签: entity-framework ef-code-first


    【解决方案1】:
     modelBuilder.Entity<ThisT>()       //configure model for entity type <T>
    
    .HasRequired(c => c.FriendOne)         // if a field, ef will create on DB as Not Null, and check in context  
                                           // if it is a navigation entity, then an underlying FK field will be marked as Not null .  
                                         // A new field will be introduce to manage this if not declared
    
    
        .WithMany()       // the target of foreign key can many Entity<t> pointing at it.
                          // The Many target could also have ICOllection<ThisT>.
                          // ie .withMany(MainT=>MainT.BucketOfThem) 
                         // leave it empty if the other side doesnt track related
    
    
        .HasForeignKey(u => u.RelationshipId); // dont create a field, I have one already..
                         // the Key to Table behind FriendOne is called RelationshipId
    

    withMany 上的标准 EF 文档知道调用是链式的。 即首先你是 HasRequired,然后是 WithMany。 所以你处于 1:M 配置模式。

    /// <summary>
    /// Configures the relationship to be required:many with a navigation property on the other side of the relationship.
    /// 
    /// </summary>
    /// <param name="navigationPropertyExpression">An lambda expression representing the navigation property on the other end of the relationship. C#: t =&gt; t.MyProperty VB.Net: Function(t) t.MyProperty </param>
    /// <returns>
    /// A configuration object that can be used to further configure the relationship.
    /// </returns>
    

    【讨论】:

    • 谢谢 phil - “FriendOne 背后的钥匙就在这里” - 这是什么意思?
    • 查看编辑 - HASForeignKey 表示我的表中有 FK 字段,请使用它而不是创建额外的字段
    猜你喜欢
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多