繁体   English   中英

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

[英]System.Data.SqlClient.SqlException: Invalid column name 'GenreId'

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

我收到一个错误: 错误这是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; }

这是DbSets:

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

这是表:表中的

所以当我在这里调试项目时是例外:错误=函数评估需要所有线程运行。 调试

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

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

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

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

[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);

ApplicationDbContext中的OnModelCreating方法中添加它。

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

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

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

[ForeignKey("Genre_Id")]

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM