实体框架具有额外属性

时间:2017-11-01 15:07:25

标签: entity-framework

我有以下型号用户(Id,名称)和朋友(User_Id,Friend_Id,日期)。 我的用户实体:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

如何为Friend表创建实体上下文?

1 个答案:

答案 0 :(得分:1)

你可以从这些方面开始。

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Friend> Friends { get; set; }
}

public class Friend
{
    [Key, Column(Order=0)]
    public int User_Id { get; set; }

    [Key, Column(Order=1)]
    public int Friend_Id { get; set; }    

    public DateTime FriendshipDate { get; set; }

    [ForeignKey("User_Id")]
    public User User { get; set; }

    [ForeignKey("Friend_Id")]
    public User UserFriend { get; set; }
}

编辑:实际上你可能需要重命名朋友导航,这样它就不会与类名冲突,但是流利的等价物将是:

class MyContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Friend> Friends { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Friend>()
            .HasKey(f => new { f.User_Id, f.Friend_Id});

        modelBuilder.Entity<Friend>()
            .HasRequired(f => f.User)
            .WithMany()
            .HasForeignKey(f => f.User_id);

        modelBuilder.Entity<Friend>()
            .HasRequired(f => f.UserFriend)
            .WithMany()
            .HasForeignKey(f => f.Friend_Id);

    }
}