我正在尝试在以下对象之间创建多对多关系:
public class Classified{
[Key]
public int Id {get;set;}
public string details {get;set;}
public ICollection<ClassifiedRating> Ratings {get;set;}
}
public class User{
[Key]
public int Id {get;set;}
public string Name {get;set;}
}
public class ClassifiedRating{
[Key]
public User Rater {get;set;}
[Key]
public Classified Classified {get;set;}
public int rating {get;set;}
}
运行时收到以下错误:
One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'ClassifiedRating'
has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'ClassifiedRating'
is based on type 'RateUser' that has no keys defined.
(“\ t”也出现在错误信息中,虽然我怀疑它是否相关,但它有点奇怪......)
答案 0 :(得分:3)
据我所知,密钥必须是字符串,整数类型或Guid对象。基本上这会迫使你总是为你想要存储的每个类都有一个人工键,但通常这是一个好主意。尝试给ClassifiedRating
一个整数键,而不是尝试使用类User
。
答案 1 :(得分:1)
ClassifiedRating
应如下所示:
public class ClassifiedRating
{
[Key, Column(Order = 0)]
public int RaterId { get; set; }
[Key, Column(Order = 1)]
public int ClassifiedId { get; set; }
public User Rater {get;set;}
public Classified Classified { get; set; }
public int rating { get; set; }
}
命名约定将检测复合主键的两个部分作为其他两个表的外键,您应该在模型中获得所需的两个一对多关系。