gpt4 book ai didi

c# - 实体类型 ‘Business_attrib2object’ 具有使用数据注释定义的复合主键。要设置复合主键,请使用 Fluent API

转载 作者:太空宇宙 更新时间:2023-11-03 20:51:27 25 4
gpt4 key购买 nike

我使用流畅的 API 设置复合主键,当我尝试创建 ClassesController(使用 Entity Framework 的 View 的 MVC Controller )时,它仍然是一个错误。

声明类类:

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

数据库上下文:

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

创建 Controller : Creating controller错误: Error message

最佳答案

如果你用过这个:

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

关于c# - 实体类型 ‘Business_attrib2object’ 具有使用数据注释定义的复合主键。要设置复合主键,请使用 Fluent API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54754676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com