C# EF代码首先,从多对多关系公开链接表/对象?
我试图将EF代码首先在多对多关系中自动创建的链接类作为一个单独的对象公开,因为该链接对象需要在其他类中引用,但是我似乎在获取数据库中存在的数据时遇到了问题 我有以下3个对象:C# EF代码首先,从多对多关系公开链接表/对象?,c#,entity-framework,ef-code-first,many-to-many,C#,Entity Framework,Ef Code First,Many To Many,我试图将EF代码首先在多对多关系中自动创建的链接类作为一个单独的对象公开,因为该链接对象需要在其他类中引用,但是我似乎在获取数据库中存在的数据时遇到了问题 我有以下3个对象: public class Role : Entity { public virtual ICollection<User> Users { get; set; } public string Name { get; set; } public string Description {
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; }
}
我不想在此类中单独存储User和Role对象,因为这样它们就不会紧密耦合,数据可能会孤立。您不需要在代码中显式创建
UserRole
实体。由于您在用户
中具有角色
的导航属性,并且在角色
中具有用户
的导航属性,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; }
}
我在帖子中说,我需要公开链接对象,因为它需要在其他对象中引用。我不想把用户和角色对象放在那些其他对象中,因为它们是解耦的。@DOTang:你是说你想把链接表UserRoles(导航类)作为另一个类的属性吗?您是否打算将其用作用户和角色以外的属性?哪个表和它是什么关系?它之所以要创建两个表,是因为在用户和角色中有两个naigational属性指向彼此。是的,这就是我要说的。我用另一门课更新了我的帖子。我明白了为什么要创建两个表,一个是自动创建的,另一个是我手动创建的,基本上跟踪相同的信息。那么,我怎样才能使EF使用我的作为链接表,并且它仍然是公开的(这样我就可以引用另一个类中的UserRole作为导航属性)?这很简单,我正在寻找一些方法来克服这一点,通过覆盖默认映射。。。
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; }
}
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);
}