c# - 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; }
这是表格: 表格中的列
因此,当我在这里调试项目时出现异常:错误 = 函数评估需要所有线程运行。 调试
解决方案
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; }
推荐阅读
- python - Python 正则表达式返回不匹配
- javascript - 如何用剧作家调用页面功能?
- php - 如何写 WHERE 引用下拉列表选择?
- vuexfire - Vuexfire:bindFirestoreRef 触发多少次读取?
- php - Foreach with Table - PHP 和 Leaguepedia API
- sql - 如果未设置值,SQLite 将具有匹配校验和的记录设置为相同的值
- flutter - 使用 Positioned inside Stack 无法正常工作
- javascript - 重新加载数据表jquery时处理指示器不起作用
- acumatica - Acumatica:是否有可能以及如何在 AR521000 屏幕中自定义网格?
- c# - 通过 _Layout.cshtml 中的 ASP.NET Core 本地化在 ASP.NET Core 中的翻译问题