Sve*_*ang 3 c# many-to-many entity-framework ef-code-first
我试图公开EF代码首先在多对多关系中自动创建的链接类作为单独的对象,因为该链接对象需要在其他类中引用,但是我似乎遇到了获取存在于其他类中的数据的问题.数据库.
我有以下3个对象:
public class Role : Entity
{
public virtual ICollection<User> Users { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Permission> Permissions { get; set; }
}
public class User: Entity
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
public class UserRole : Entity
{
public User User { get; set; }
public Role Role { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这将创建以下表:

现在我可以看到问题是它正在创建一个RoleUsers表,当它不应该而且应该只使用我的UserRoles表.如何强制链接表,UserRoles以便我可以在EF中显示该链接对象,以便我可以在其他对象中使用它?
另外,在编写查询时,我将如何遍历对象?我是否仍然可以使用User.Roles.Any(y => y.Name =="blah"),或者我现在必须通过去User.UserRoles.Any进行查询(y => y.Role.Name = ="等等")?我想在同时暴露链接对象的同时不可能保持透明链接?
编辑:引用UserRole作为导航属性的类之一如下所示:
public class UserRoleEntity : Entity
{
public UserRole UserRole { get; set; }
public Guid EntityId { get; set; }
public EntityType EntityType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我不想在这个类中单独存储User和Role对象,因为它们没有紧密耦合,数据可能是孤立的.
您不需要UserRole在代码中显式创建实体.由于您具有Rolesin Users和Usersin 的导航属性Roles,EF将自动在它们之间创建关系.
编辑:如果你想创建链接表并将其用作另一个类的属性,你可以这样做.
public class User
{
public int UserID { set; get; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
public class Role
{
public int RoleID { set;get;}
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<UserRole> UserRoles { get; set; }
}
public class UserRole
{
public int UserRoleID { set; get; }
public virtual User User { get; set; }
public virtual Role Role { get; set; }
}
public class AnotherEntity
{
public int ID { set; get; }
public int UserRoleID { set; get; }
}
Run Code Online (Sandbox Code Playgroud)
你会像这样创建你的表格

你是对的,你必须像这样访问它
StringBuilder stRoleNames = new StringBuilder();
var user1 = dbContext.Users.Where(x => x.UserID == 34).SingleOrDefault();
var userRoles = user1.UserRoles;
foreach (var userRole in userRoles)
{
stRoleNames.Append(userRole.Role.Name);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1637 次 |
| 最近记录: |