【问题标题】:EntityType has no key definedEntityType 没有定义键
【发布时间】:2014-03-22 21:20:03
【问题描述】:

C# 代码(EF6 代码优先):

public class ProjectSourceProject
{
    [Key, Column(Order = 0)]
    //[Key, Column(Order = 0), ForeignKey("ProjectSource")]
    //[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ProjectSource_id { get; set; } // { get; set; } was missing :)

    [Key, Column(Order = 1)]
    //[Key, Column(Order = 1), ForeignKey("Project")]
    //[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Project_id { get; set; } // { get; set; } was missing :)

    //public virtual ICollection<Project> projects { get; set; }
    //public virtual ICollection<ProjectSource> projectSources { get; set; }

    public ProjectSourceProject()
    {
        //projects = new HashSet<Project>();
        //projectSources = new HashSet<ProjectSource>();
    }
}

数据库:

One or more validation errors were detected during model generation:

EntityType 'ProjectSourceProject' has no key defined. Define the key for this EntityType.

C#代码2:

public class ProjectSourceProject
{
    //[Key]
    //[Key, Column(Order = 0)]
    public int ProjectSource_id { get; set; } // { get; set; } was missing :)

    //[Key]
    //[Key, Column(Order = 1)]       
    public int Project_id { get; set; } // { get; set; } was missing :)

    public ProjectSourceProject()
    {

    }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<ProjectSourceProject>()
        .HasKey(psp => new { psp.ProjectSource_id, psp.Project_id });

    //base.OnModelCreating(modelBuilder);
}

得到以下奇怪的错误:

The properties expression 'psp => new <>f__AnonymousType0`2(ProjectSource_id = psp.ProjectSource_id, Project_id = psp.Project_id)' is not valid. The expression should represent a property: C#: 't => t.MyProperty'  VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }'  VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.

已编辑:问题已修复,感谢 Moho :)

这在这两种情况下都有效。

【问题讨论】:

    标签: c# sql-server entity-framework


    【解决方案1】:

    制作 PK 字段属性...

    [Key, Column(Order = 0), ForeignKey("ProjectSource_projects_Source")]
    public int ProjectSource_id { get; set;} // add { get; set; }
    
    [Key, Column(Order = 1), ForeignKey("ProjectSource_projects_Target")]
    public int Project_id { get; set;} // add { get; set; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      • 2016-03-16
      • 2013-08-04
      • 2012-12-10
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多