c# - Entity Framework 代码优先 - 定义此 EntityType 的键

标签 c# entity-framework ef-code-first entity-framework-4.1

您好,我计划在我的一个项目中测试 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/

相关文章:

entity-framework - 使用 Entity Framework 4将N​​otes表与多个实体表相关

c# - linq - 如何查找一个集合的键列是否是另一个集合的子集?

c# - 每个表只允许一个标识列

c# - 使 EF 将字节数组映射为二进制而不是 varbinary

c# - 在哪里以及如何使用嵌套类?

c# - 从 IP 摄像头获取位图图像,UWP

c# - 如何隐藏RadioButton控件中的圆圈?

c# - 导航属性的唯一约束

entity-framework - 代码优先 Entity Framework - 同一个表的多个外键

c# - 如何使用公共(public)交通和消息数据干净地注册类