c# - 列名称无效。该名称从未在代码中实现

标签 c# asp.net asp.net-mvc entity-framework linq

我有一个简单的程序,我正在设置它以用于单元测试。出于某种原因,Entity Framework 对我大喊大叫,并出现以下错误:Invalid column name 'Author_Id'.

问题是我没有名为 Author_Id 的列,该列不在项目中,不在模型中,也不在数据库的表中。出于某种原因,它将 _Id 部分添加到我搜索的内容的末尾。

示例:如果我将其设置为搜索 Author,我会得到 Author_IdAuthorId 变为 AuthorId_IdAuthor_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/

相关文章:

c# - 无法使用 SelectedItem = null - MVVM 清除 ListBox 选择

c# - 使用 ASP MVC 将字符串从 <form> 传递到 Controller

c# - 将不同的模型类型从 Controller 传递到 View 是好的做法吗?

c# - iTextSharp 出现 "Specified method is not supported"错误

c# - 为什么我不能在 C# 中的 char 数组上使用 .ToString() 方法?

c# - ASP :NET MVC Route Config allow #

.net - 使用 ASP.NET 和 Ajax 创建共享工作区

asp.net - ASP.NET 中模态弹出窗口的最佳选择?

c# - 什么是锁定线程的正确方法?

c# - 使用 Autofac 在两个 Controller 中获取不同的界面