我有一个简单的程序,我将其设置为与单元测试一起使用。出于某种原因,实体框架对我大吼大叫,出现以下错误: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; }
}
My Book模型是这样的:
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; }
}
答案 0 :(得分:3)
您有两个导航属性,而不是一个导航属性和一个外键属性。
不应该这样:
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; }
}
答案 1 :(得分:2)
Include
方法用于加载相关实体,而不是单个列(如AuthorId
)。改为包含导航属性。
替换
var books = db.Books.Include(b => b.AuthorId);
通过
var books = db.Books.Include(b => b.Author);
注意:无论如何都会加载authorId
,因为它只是books表中的一列。
答案 2 :(得分:1)
对不起伙计们。我有点想先同时使用代码和数据库。我不得不删除旧表并使用迁移重新创建它们。然后我也有2个不同的dbContexts。一个用于身份,一个用于我。而且,关系都搞砸了。无论如何,如果有人有类似的问题,请检查你的关系。首先使用数据库或首先使用代码。不要像我一样混合它们。