使用数据注释的多对多映射 [英] Many to Many Mapping Using Data Annotations

查看:94
本文介绍了使用数据注释的多对多映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[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

I map these tables using EntityTypeConfiguration and it triggers OnModelCreate

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

我想知道如果有一种方法将其映射到Role或UserMaster类中。我们可以使用

I wonder If there Is a way to map them in the class Role or UserMaster. We can use

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

我们可以做映射的东西吗?

Could we do the mapping thing also?

推荐答案

如果要使用数据注释来首先定义实体框架代码,以达到多对多关系,则必须添加交换类,如下所示:

If you want to customize entity framework code first for many to many relationship using data annotation, you must add junction class as the following :

[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; }
}

然后相关类必须更改为:

and then related classes must be changed to :

[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; }
}

,还可以看到这个

这篇关于使用数据注释的多对多映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆