entity-framework - 使用模型构建器指定 HasForeignKey?

标签 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.Entity<Relationship>()
        .HasRequired(c => c.FriendOne)
        .WithMany()
        .HasForeignKey(u => u.FriendOneId);

还有这个:

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

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

最佳答案

 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>

关于entity-framework - 使用模型构建器指定 HasForeignKey?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19920412/

相关文章:

.NET Entity Framework 和事务

asp.net-mvc - 如果有的话,什么设计模式在实现基于用户的记录级权限方面有用?

c# - 如何将 "Provider Connection String"与 EF (EDMX) 元数据信息分开?

entity-framework - Entity Framework : one to zero or one relationship with foreign key on principal

entity-framework - Entity Framework 代码优先,自定义,多对多关系中的附加字段

c# - 如何强制 EF 代码首先重新创建数据库?

sql-server - 尝试部署 Entity Framework 代码优先应用程序但运气不佳?最佳部署策略?

entity-framework - EF 4 中 "include foreign key columns in the model"选项的优缺点是什么

c# - Entity Framework 中是否存在 NHibernate.ToFuture() 扩展方法的模拟?

MySQL 5.5 + .NET 连接器 + Entity Framework + 迁移 = FormatException