加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – EntityType没有定义键

发布时间:2020-12-15 22:01:45 所属栏目:百科 来源:网络整理
导读:C#代码(EF6代码优先): public class ProjectSourceProject{ [Key,Column(Order = 0)] //[Key,Column(Order = 0),ForeignKey("ProjectSource")] //[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int ProjectSource_id { get; set;
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 }'.

编辑:问题修复,谢谢莫霍:)

这适用于这两种情况.

解决方法

制作PK字段属性……

[Key,ForeignKey("ProjectSource_projects_Source")]
public int ProjectSource_id { get; set;} // add { get; set; }

[Key,ForeignKey("ProjectSource_projects_Target")]
public int Project_id { get; set;} // add { get; set; }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读