您好,我计划在我的一个项目中测试 EF Code First。这就是我想要的。 我有三个表,结构如下
public partial class App_user
{
public int id { get; set; }
public string name { get; set; }
public string email_address { get; set; }
public string password { get; set; }
public int user_type { get; set; }
public List<Role> Roles { get; set; }
}
public partial class Role
{
public int id { get; set; }
public string name { get; set; }
}
public partial class User_role
{
public int user_id { get; set; }
public int role_id { get; set; }
public virtual Role Role { get; set; }
public virtual App_user App_user { get; set; }
}
第三张表没有主键。所以它在运行时会报错。这是错误消息 -
System.Data.Edm.EdmEntityType: : EntityType 'User_role' has no key defined. Define the key for this EntityType. System.Data.Edm.EdmEntitySet: EntityType: The EntitySet User_roles is based on type User_role that has no keys defined.
为什么会这样?有解决办法吗?
最佳答案
如果您认为您正在尝试为用户和角色之间的多对多关系建模。在这种情况下,您的模型是完全错误的。
改用这个:
public partial class App_user
{
public int id { get; set; }
public string name { get; set; }
public string email_address { get; set; }
public string password { get; set; }
public int user_type { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
public partial class Role
{
public int id { get; set; }
public string name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
这将自动创建多对多,您无需为联结表操心。如果你需要公开联结表,你必须使用这个:
public partial class App_user
{
public int id { get; set; }
public string name { get; set; }
public string email_address { get; set; }
public string password { get; set; }
public int user_type { get; set; }
public virtual ICollection<User_Role> UserRoles { get; set; }
}
public partial class Role
{
public int id { get; set; }
public string name { get; set; }
public virtual ICollection<User_Role> UserRoles { get; set; }
}
public partial class User_role
{
[Key, ForeignKey("App_user"), Column(Order = 0)]
public int user_id { get; set; }
[Key, ForeignKey("Role"), Column(Order = 1)]
public int role_id { get; set; }
public virtual Role Role { get; set; }
public virtual App_user App_user { get; set; }
}
如果您不需要其中的附加属性,则公开联结表是没有意义的。
对于您的错误 - Entity Framework 中的每个实体都必须定义主键。
关于c# - Entity Framework 代码优先 - 定义此 EntityType 的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5482670/