代码优先:EntityType'xxxx'没有定义键。添加n-to-n关系时,定义此EntityType的键

问题描述 投票:-1回答:1

我是MVC的新手,我正在按照指南制作一个首先使用代码并在Internet上进行个人用户帐户身份验证的MVC项目。但是,当我将模型更改为多对多关系时,我得到了

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 ???

c# asp.net asp.net-mvc asp.net-mvc-5 entity-framework-6
1个回答
0
投票

作者可以拥有多本书,因此您应该在作者实体中定义一组书籍:

public ICollection<Book> Books { get; set; }

实际上一本书实际上可以有超过1位作者(不确定在你的情况下它是否相同)但如果是,你应该在你的书籍实体中声明一组作者:

public ICollection<Author> Authors { get; set; }

多数民众赞成,这将产生以下表格:enter image description here

此外,如果您想了解更多,可用的确有很多来源:

祝好运!

© www.soinside.com 2019 - 2024. All rights reserved.