实体框架代码优先映射

编程入门 行业动态 更新时间:2024-10-25 16:18:15
本文介绍了实体框架代码优先映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个班,组类有许多与用户类(表示用户所属的组)的组,然后也有一对多的用户类的关系(占所有者一对多的关系一组)。

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).

我该如何映射呢?

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

tks in advance!

推荐答案

我会用流利的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 是无需对关系的两侧,但它确实定义清晰。

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

更多推荐

实体框架代码优先映射

本文发布于:2023-07-27 12:06:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1222349.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   框架   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!