用ModelBuilder指定HasForeignKey?

时间:2013-11-12 03:37:01

标签: entity-framework ef-code-first

说我有一个“关系”实体:

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,那么它之间的区别是什么:

        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将非常感激。

1 个答案:

答案 0 :(得分: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>