1

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

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 方面的任何帮助将不胜感激。

4

1 回答 1

2
 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>
于 2013-11-12T04:32:13.887 回答