First Entity Framework Mapping Code

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

How to do it?

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!

+6
source share
1 answer

I would use the free 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); } } 

This 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 not required on both sides of the relationship, but it makes the definition clearer.

+5
source

Source: https://habr.com/ru/post/886259/


All Articles