gpt4 book ai didi

c# - 使用数据注释的多对多映射

转载 作者:太空狗 更新时间:2023-10-29 21:01:54 25 4
gpt4 key购买 nike

[Table("UserMaster")]
public class UserMaster
{
public UserMaster()
{
this.Roles = new List<Role>();
}

[Key]
public int UserId { get; set; }
public string UserName { get; set; }
public ICollection<Role> Roles { get; set; }
}



[Table("Role")]
public class Role
{
public Role()
{
this.Users = new List<UserMaster>();
}
public int RoleId{ get; set; }
public string Name{ get; set; }
public ICollection<UserMaster> Users { get; set; }

}

我使用 EntityTypeConfiguration 映射这些表,它触发 OnModelCreate

this.HasMany(a => a.Roles).WithMany(b => b.Users).Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("UsersInRoles");
});

我想知道是否有办法将它们映射到 Role 或 UserMaster 类中。我们可以使用

[ForeignKey()]
[Key]
[Table()]

我们也可以做映射吗?

最佳答案

如果你想先为使用数据注释的多对多关系自定义 Entity Framework 代码,你必须添加如下连接类:

[Table("UsersInRoles")]
public class UsersInRoles
{
[Key]
[Column(Order = 1)]
[ForeignKey("UserMaster")]
public int UserId { get; set; }

[Key]
[Column(Order = 2)]
[ForeignKey("Role")]
public int RoleId { get; set; }

public UserMaster UserMaster { get; set; }
public Role Role { get; set; }
}

然后相关类必须改为:

[Table("UserMaster")]
public class UserMaster
{
public UserMaster()
{
this.Roles = new List<Role>();
}

[Key]
public int UserId { get; set; }
public string UserName { get; set; }

public ICollection<UsersInRoles> UsersInRoles { get; set; }
}



[Table("Role")]
public class Role
{
public Role()
{
this.Users = new List<UserMaster>();
}
public int RoleId{ get; set; }
public string Name{ get; set; }

public ICollection<UsersInRoles> UsersInRoles { get; set; }
}

另见 this .

关于c# - 使用数据注释的多对多映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18648600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com