c# - Entity Framework Code First 通过 DataAnnotations 实现多对多关系

标签 c# entity-framework many-to-many ef-code-first data-annotations

我正在尝试在以下对象之间创建多对多关系:

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 对象。基本上,这会迫使您始终为每个要存储的类设置一个人工 key ,但通常这是个好主意。尝试给 ClassifiedRating 一个整数键,而不是尝试使用类 User

关于c# - Entity Framework Code First 通过 DataAnnotations 实现多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9729168/

相关文章:

c# - 在 SQL Server/LINQ to SQL 中查询 ae 匹配 æ

c# - 种子方法如何使用foreach循环?

mysql - 如何为具有多对多关系的 2 个 MySQL 表创建默认关系?

c# - Java RSA 加密

c# - 使用组合器 lamba 合并 C# 中的 2 个列表

c# - 另一个代码页检测问题

asp.net - 单网站多数据库、数据库切换

entity-framework - 映射到 View 的对象的意外迁移

python - related_name 是做什么用的?

grails - 如何在没有belongsTo的情况下处理Grails中的多对多?