实体框架中的模型多对多(Model Many to many in Entity Framework)

编程入门 行业动态 更新时间:2024-10-21 23:03:39
实体框架中的模型多对多(Model Many to many in Entity Framework)

我需要在EF中模拟多对多的关系。 我经常遇到的答案要求两个实体互相引用。

这是我的情况。

我有一个Role实体,它可以有多个权限(“权限实体”。)Role将有一个名为权限的列表。另一方面,一个权限可以属于多个角色,但它没有role的引用属性。

我该如何建模呢?

另外,我可以使用Role级联新的权限吗?

I need to model a Many to many relation in EF. The answer I usually come across requires both entities to have each others reference.

Here is my case.

I have a Role entity, which can have multiple permissions("Permission entity). Role will have a list called permissions. On the other hand one permission can belong to multiple roles but it does not have a reference property for role.

How can I model it?

Also, can I cascade a new permission with Role?

最满意答案

使用Code-First,您可以使用此建模:

public class Role { public Role() { this.Premission = new HashSet<Premission>(); } public int RoleId { get; set; } public string RoleName { get; set; } public virtual ICollection<Premission> Premissions { get; set; } } public class Premission { public Premission() { this.Role = new HashSet<Role>(); } public int PremissionId { get; set; } public string PremissionName { get; set; } public virtual ICollection<Role> Roles{ get; set; } }

使用Fluent Api,您可以将其映射为:

protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Role>() .HasMany<Premission>(s => s.Premissions) .WithMany(c => c.Roles) .Map(cs => { cs.MapLeftKey("RoleRefId"); cs.MapRightKey("PremissionRefId"); cs.ToTable("Role_Premission"); }); }

Using Code-First you can go with this modeling:

public class Role { public Role() { this.Premission = new HashSet<Premission>(); } public int RoleId { get; set; } public string RoleName { get; set; } public virtual ICollection<Premission> Premissions { get; set; } } public class Premission { public Premission() { this.Role = new HashSet<Role>(); } public int PremissionId { get; set; } public string PremissionName { get; set; } public virtual ICollection<Role> Roles{ get; set; } }

Using Fluent Api you can map it like:

protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Role>() .HasMany<Premission>(s => s.Premissions) .WithMany(c => c.Roles) .Map(cs => { cs.MapLeftKey("RoleRefId"); cs.MapRightKey("PremissionRefId"); cs.ToTable("Role_Premission"); }); }

更多推荐

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

发布评论

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

>www.elefans.com

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