【问题标题】:Entity Framework CodeFirst with many-to-many relationship via DataAnnotations通过 DataAnnotations 具有多对多关系的实体框架代码优先
【发布时间】:2012-03-15 22:32:31
【问题描述】:

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

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”也出现在错误消息中,虽然我怀疑它是否相关,但有点奇怪......)

【问题讨论】:

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


    【解决方案1】:

    据我所知,键必须是字符串、整数类型或 Guid 对象。基本上,这会迫使您始终为要存储的每个类都有一个人工密钥,但通常这是一个好主意。尝试给 ClassifiedRating 一个整数键,而不是尝试使用类 User

    【讨论】:

    • 是的,这是正确的,数据库中的 PK 必须在实际列上,并且模型中的 User 属性仅用于导航
    • 谢谢,我不知道。它有效,现在又发现了另一个错误
    【解决方案2】:

    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; }
    }
    

    命名约定会将复合主键的两个部分检测为其他两个表的外键,并且您应该在模型中获得所需的两个一对多关系。

    【讨论】:

    • 我将virtual 用于UserClassified 对象
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 2013-03-17
    • 2012-04-03
    • 2013-03-14
    相关资源
    最近更新 更多