本文介绍了指定带有ModelBuilder的HasForeignKey?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个关系实体:

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映射这些关系,两者之间有什么区别

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

然后:

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

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

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.

推荐答案

 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

标准EF文档在with上很多人都知道该呼叫已链接。
,即首先是一个HasRequired,然后是WithMany。
,因此您处于1:M配置模式。

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>

这篇关于指定带有ModelBuilder的HasForeignKey?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-25 08:26