在EF 4.1中再添加一个导航类型

时间:2011-04-08 19:40:32

标签: c# .net code-first ef-code-first entity-framework-4.1

我对下面的实体关系有点困惑。因为它比一个用户关系更多。我觉得有些不对劲。这有什么不对吗?

public class Subject: Entity
{
    public Advert()
    {
        CreateDate = DateTime.Now;
    }
    public virtual User Owner{ get; set; }
    public virtual List<User> Voters{ get; set; }
    public virtual List<User> Followers{ get; set; }
}

1 个答案:

答案 0 :(得分:2)

我不确定这是否适用于您的列表,这应该是EF CodeFirst标准的ICollections。

您可能还希望使用继承来区分不同类型的用户,或者为关注者和选民提供不同的实体。

您需要使用WithMany()

进行映射

这将允许您指定关系的foreignKey

http://weblogs.asp.net/manavi/archive/2011/01/23/associations-in-ef-code-first-ctp5-part-3-one-to-one-foreign-key-associations.aspx

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
                .HasRequired(a => a.BillingAddress)
                .WithMany()
                .HasForeignKey(u => u.BillingAddressId);

    modelBuilder.Entity<User>()
                .HasRequired(a => a.DeliveryAddress)
                .WithMany()
                .HasForeignKey(u => u.DeliveryAddressId);
}