System.Data.SqlClient.SqlException:无效的列名称“ GenreId”

时间:2018-11-05 21:53:33

标签: c# asp.net asp.net-mvc entity-framework-6 sqlexception

我是ASP.NET的新手,正在学习MVC和EF。我没有任何现有的答案可以解决我的问题,请提供帮助。使用代码优先。

我得到一个错误:          Error 这是Controller中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; }

这是表格: Columns in table

因此,当我调试项目时,这里是例外: 错误=函数评估要求所有线程都运行。 Debug

2 个答案:

答案 0 :(得分:0)

BookGenre之间的关系问题。请阅读this文章。

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

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

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

Book

使用Fluent API进行一对多的关系:

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

通过modelBuilder.Entity<Book>() .HasRequired(e => e.Genre) .WithMany(d => d.books); 中的OnModelCreating方法添加此内容。

,还为{strong>一对多关系(如果未添加)在ApplicationDbContext类的下面添加行:

Genre

答案 1 :(得分:-1)

将以下注释添加到public Genre Genre { get; set; }

[ForeignKey("Genre_Id")]

这应该有所帮助,因为EF在数据库中生成了错误的外键名称。 通过添加注释,您可以告诉EF数据库中列的命名方式。

相关问题