Specifying HasForeignKey with ModelBuilder?

早过忘川 提交于 2019-12-13 21:25:09

问题


Say I have a "Relationship" entity:

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; }
}

If I want to map these relationships with ModelBuilder, what is the difference between this:

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

And this:

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

I get confused with this every time I'm setting up a new DB. The documentation I've found and answers on SO seem to conflict one another on this... any help in understanding how to use HasForeignKey would be much appreciated.


回答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

standard EF docu on withMany knows that call is chained. ie first you a HasRequired, then a WithMany. so you are in 1:M config mode.

/// <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>


来源:https://stackoverflow.com/questions/19920412/specifying-hasforeignkey-with-modelbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!