实体类型“ Business_attrib2object”具有使用数据注释定义的复合主键。要设置复合主键,请使用fluent API

时间:2019-02-18 20:12:07

标签: c# entity-framework asp.net-core

我使用fluent API设置了复合主键,当我尝试创建ClassesController(带有使用实体框架的视图的MVC控制器)时,这仍然是一个错误。

声明类类:

public partial class Classes
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Classes()
    {
        this.Business_attrib2object = new HashSet<Business_attrib2object>();
        this.Objects = new HashSet<Objects>();
    }
    [Key]
    public System.Guid IdClass { get; set; }
    public string Name { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Business_attrib2object> Business_attrib2object { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Objects> Objects { get; set; }
}

声明Business_attrib2object类:

 public partial class Business_attrib2object
{
    [Key]
    public System.Guid IdClass { get; set; }
    [Key]
    public System.Guid IdAttribute { get; set; }

    public Nullable<System.Guid> IdAuthor { get; set; }

    public virtual Attributes Attributes { get; set; }
    public virtual Classes Classes { get; set; }
}

DBContext:

public class Business_attrib2objectContext : DbContext
{
    public DbSet<Business_attrib2object> Business_attrib2object { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Business_attrib2object>().HasKey(ba => new { ba.IdClass, ba.IdAttribute });      
    }

    public Business_attrib2objectContext(DbContextOptions<Business_attrib2objectContext> options)
        : base(options)
    {
        Database.EnsureCreated();
    }
}

创建控制器: Creating controller 错误: Error message

2 个答案:

答案 0 :(得分:2)

不确定混乱是什么。该错误是明确的。您有指定复合主键的数据属性,而您不能这样做。您已经在上下文中获得了必要的流畅配置,因此只需删除[Key]类上的两个Business_attrib2object数据属性即可。

答案 1 :(得分:0)

如果您使用过此方法:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Business_attrib2object>().HasKey(ba => new { ba.IdClass, ba.IdAttribute });      
}

您不需要这个:

public partial class Business_attrib2object
{
    [Key]
    public System.Guid IdClass { get; set; }
    [Key]
    public System.Guid IdAttribute { get; set; }

    ...

只需删除它应该起作用的[Key]属性:

public partial class Business_attrib2object
{
    public System.Guid IdClass { get; set; }
    public System.Guid IdAttribute { get; set; }

    public Nullable<System.Guid> IdAuthor { get; set; }

    public virtual Attributes Attributes { get; set; }
    public virtual Classes Classes { get; set; }
}