【发布时间】:2019-08-24 12:21:46
【问题描述】:
我是 MVC 新手,我正在按照指南制作 MVC 项目,首先使用代码并在 Internet 上进行个人用户帐户身份验证。但是当我将模型更改为多对多关系时,我得到了
MyFirstASP_MVC_API.Models.BookAuthor: : EntityType 'BookAuthor' 没有定义键。定义此 EntityType 的键。 BookAuthors: EntityType: EntitySet 'BookAuthors' 基于没有定义键的类型'BookAuthor'。
这是我的课程
public class Author
{
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[StringLength(1000)]
public string Description { get; set; }
public bool IsActive { get; set; }
public ICollection<BookAuthor> BookAuthors { get; set; }
}
public class Book
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
[Required]
[Index(IsUnique = true)]
[StringLength(20)]
public string ISBN { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public Nullable<DateTime> CreatedDate { get; set; }
public Nullable<DateTime> ModifiedDate { get; set; }
public bool IsActive { get; set; }
public ICollection<BookAuthor> BookAuthors { get; set; }
public ICollection<BookCategory> BookCategories { get; set; }
public Publisher Publisher { get; set; }
public int PublisherId { get; set; }
}
public class BookAuthor
{
public int BookId { get; set; }
public Book Book { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }
}
我使用了IdentityModel.cs中的ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Book> Books { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Publisher> Publishers { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<BookCategory> BookCategories { get; set; }
public DbSet<BookAuthor> BookAuthors { get; set; }
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
我读过一些关于解决问题的文章,他们使用了OnModelCreating,但没有人使用ApplicationDbContext,所以我不知道我是否应该将它添加到ApplicationDbContext。
那我该怎么办,需要新建DbContext吗???
【问题讨论】:
-
EntityType has no key defined error -
Place a [Key] annotation on top of your chosen property.的可能重复 -
@mjwills 我尝试在我的
BookId和AuthorId顶部添加 [Key] 但 VS 显示了这个而不是Unable to determine composite primary key ordering for type 'MyFirstASP_MVC_API.Models.BookAuthor'. Use the ColumnAttribute (see http://go.microsoft.com/fwlink/?LinkId=386388) or the HasKey method (see http://go.microsoft.com/fwlink/?LinkId=386387) to specify an order for composite primary keys -
那个错误告诉你该怎么做@V.Lap。你试过它的建议了吗?
-
对于 HasKey 方法,就像我在上面注意到的那样,我不知道我可以覆盖由 VS 自动生成的 ApplicationDbContext 中的 OnModelCreating 方法,因为我在网上找到的所有问题都使用了另一个数据库上下文。
标签: c# asp.net asp.net-mvc asp.net-mvc-5 entity-framework-6