首页 > 解决方案 > System.Data.SqlClient.SqlException:无效的列名'GenreId'

问题描述

我是 ASP.NET 的新手,我正在学习 MVC 和 EF。我无法匹配我的问题的任何现有答案,所以请帮忙。使用代码优先。

我收到一个错误: 错误 这是控制器中 Action 方法的代码:

public ActionResult Index()
    {
        var book = _context.Books.Include(b => b.Genre).ToList();
        return View(book);
    }

这是 Book.cs 模型:

public class Book
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    [Required]
    [StringLength(17)]
    public string ISBN { get; set; }

    [Required]
    public string Author { get; set; }

    [Required]
    public string Publisher { get; set; }

    public Genre Genre { get; set; }

    [Required]
    [Display(Name = "Genre")]
    public byte GenreId { get; set; }

    [Display(Name = "Published Year")]
    public DateTime PublishedYear { get; set; }

    [Display(Name = "Release Date")]
    public DateTime ReleaseDate { get; set; }

    [Display(Name = "Number in Stock")]
    [Range(1, 20, ErrorMessage = "The field Number in Stock must be between 1 and 20")]
    public byte NumberInStock { get; set; }

以下是 DbSet:

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Book> Books { get; set; }
    public DbSet<MembershipType> MembershipTypes { get; set; }
    public DbSet<Genre> Genres { get; set; }

这是表格: 表格中的

因此,当我在这里调试项目时出现异常:错误 = 函数评估需要所有线程运行。 调试

标签: c#asp.netasp.net-mvcentity-framework-6sqlexception

解决方案


Book和之间的关系问题Genre。请阅读这篇文章。

类中的导航属性 ( Genre)Book返回对对象的引用。Genre另一方面,Genre类中的导航属性返回books集合。

book模型在Genre_Id表中book创建了外键。您可以将 包含foreign Key Property在依赖类 ( Book) 中。

使用数据注释的一对多关系:

[ForeignKey("GenreId ")]
public Genre Genre { get; set; }
[Required]
[Display(Name = "Genre")]
public byte GenreId { get; set; }

使用 Fluent API 的一对多关系:

modelBuilder.Entity<Book>()
            .HasRequired(e => e.Genre)
            .WithMany(d => d.books);

OnModelCreating你的ApplicationDbContext.

并在Genre类中为一对多关系添加以下行(如果您未添加):

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

推荐阅读