实体框架CodeFirst通过DataAnnotations实现多对多关系
本文关键字:关系 实现 DataAnnotations 框架 CodeFirst 通过 实体 | 更新日期: 2023-09-27 18:27:53
我正在尝试在以下对象之间创建多对多关系:
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"也出现在错误消息中,尽管我怀疑它是否相关,但这有点奇怪……)
据我所知,键必须是字符串、整数类型或Guid对象。基本上,这会迫使您为想要存储的每个类始终有一个人工密钥,但通常这是一个好主意。尝试给ClassifiedRating
一个整数键,而不是尝试使用类User
。
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; }
}
命名约定将检测组合主键的两个部分作为其他两个表的外键,并且您应该在模型中获得所需的两个一对多关系。