我有一个简单的程序,我正在设置它以用于单元测试。出于某种原因,Entity Framework 对我大喊大叫,并出现以下错误:Invalid column name 'Author_Id'.
问题是我没有名为 Author_Id 的列,该列不在项目中,不在模型中,也不在数据库的表中。出于某种原因,它将 _Id
部分添加到我搜索的内容的末尾。
示例:如果我将其设置为搜索 Author
,我会得到 Author_Id
。 AuthorId
变为 AuthorId_Id
,Author_Id
变为 Author_Id_Id
。
我不知道我在这里做错了什么。我搜索了整个解决方案,但一无所获。
它告诉我我的错误在这里:
public ViewResult Index()
{
var books = db.Books.Include(b=>b.AuthorId);
ViewBag.AlbumCount = books.Count();
return View(books.OrderBy(b => b.Author.Id).ToList());
//^^^^ Return is supposed to be doing the error. Fetching Name or
}
我的作者模型是这样的:
public class Author
{
[Key]
public int Id { get; set; }
[Display(Name = "Author")]
public string Name { get; set; }
[Display(Name = "Date of birth")]
public DateTime? DateOfBirth { get; set; }
[Display(Name = "Date of death")]
public DateTime? DateOfDeath { get; set; }
public ICollection<Book> Books { get; set; }
}
我的书本模型是这样的:
public class Book
{
[Key]
public int Id { get; set; }
[Display(Name = "Select author")]
public Author AuthorId { get; set; }
[Required]
public string Title { get; set; }
[Display(Name = "Publication date")]
public DateTime? PublicationDate { get; set; }
public float? Edition { get; set; }
public Author Author { get; set; }
}
最佳答案
您有两个导航属性,而不是一个导航属性和一个外键属性。
不应该这样:
public class Book
{
[Key]
public int Id { get; set; }
[Display(Name = "Select author")]
public Author AuthorId { get; set; }
[Required]
public string Title { get; set; }
[Display(Name = "Publication date")]
public DateTime? PublicationDate { get; set; }
public float? Edition { get; set; }
public Author Author { get; set; }
}
成为
public class Book
{
[Key]
public int Id { get; set; }
[Display(Name = "Select author")]
public int AuthorId { get; set; }
[Required]
public string Title { get; set; }
[Display(Name = "Publication date")]
public DateTime? PublicationDate { get; set; }
public float? Edition { get; set; }
[ForeignKey("AuthorId")]
public Author Author { get; set; }
}
?
关于c# - 列名称无效。该名称从未在代码中实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47911484/