实体框架代码优先 - 定义此EntityType的密钥

Muk*_*esh 26 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; }
    }
Run Code Online (Sandbox Code Playgroud)

在第三个表中没有主键.因此它在运行时出错.这是错误信息 -

System.Data.Edm.EdmEntityType :: EntityType'User_role'没有定义键.定义此EntityType的键.System.Data.Edm.EdmEntitySet:EntityType:EntitySet User_roles基于没有定义键的User_role类型.

为什么会这样?这有解决方案吗?

Lad*_*nka 37

如果认为您正在尝试模拟用户和角色之间的多对多关系.在这种情况下,您的模型完全错误.

请改用:

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; }
}
Run Code Online (Sandbox Code Playgroud)

这将自动创建多对多,您不需要打扰连接表.如果需要公开联结表,则必须使用:

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; }
}
Run Code Online (Sandbox Code Playgroud)

如果您不需要其他属性,则公开联结表是没有意义的.

对于您的错误 - 实体框架中的每个实体都必须定义主键.

  • System.ComponentModel.DataAnnotations(它还有单独的程序集). (4认同)

Yng*_*sen 19

你可以这样做:

public partial class User_role
{
    [Key]
    public int user_id { get; set; }
    [Key]
    public int role_id { get; set; }
    public virtual Role Role { get; set; }
    public virtual App_user App_user { get; set; }
}
Run Code Online (Sandbox Code Playgroud)