简体   繁体   English

实体框架代码第一映射

[英]Entity Framework Code First Mapping

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). 我有两个类,Group类与User类有多对多关系(表示用户所属的组),然后该组与用户类(表示组的所有者)之间也存在一对多的关系)。

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! 事先提前!

I would use fluent API: 我会使用流畅的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. 在关系的两个方面都不需要InverseProperty ,但它的定义更清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM