Entity Framework Code First Mapping

旧时模样 提交于 2019-12-21 01:39:11

问题


I have two classes, the Group class has a many to many relationship with the User class (representing the groups a user belongs to) and then the group also has a relationship of one to many with the user class (representing the owner of a group).

How can I map this?

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

    public virtual ICollection<Group> OwnedGroups { get; set; }
    public virtual ICollection<Group> Groups { get; set; }
}

public class Group
{
    public int Id { get; set; }
    public DateTime CreateDate { get; set; }
    public DateTime ModifyDate { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public bool System { get; set; }
    public int ViewPolicy { get; set; }
    public int JoinPolicy { get; set; }
    public string Avatar { get; set; }
    public int Order { get; set; }
    public int GroupType { get; set; }

    public virtual User Owner { get; set; }
    public virtual ICollection<User> Members { get; set; }
}

tks in advance!


回答1:


I would use fluent API:

public class Context : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Group> Groups { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<User>()
                    .HasMany(u => u.Groups)
                    .WithMany(g => g.Members);

        modelBuilder.Entity<User>()
                    .HasMany(u => u.OwnedGroups)
                    .WithRequired(g => g.Owner)
                    .WillCascadeOnDelete(false);
    }
}

It should also be possible with Data annotations:

public class User
{
    ...

    [InverseProperty("Owner")]
    public virtual ICollection<Group> OwnedGroups { get; set; }
    [InverseProperty("Members")]
    public virtual ICollection<Group> Groups { get; set; }
}

public class Group
{
    ...

    [InverseProperty("OwnedGroups")]
    public virtual User Owner { get; set; }
    [InverseProperty("Groups")]
    public virtual ICollection<User> Members { get; set; }
}

InverseProperty is not needed on both sides of relation but it does definition clearer.



来源:https://stackoverflow.com/questions/5720889/entity-framework-code-first-mapping

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