EF Core:如何从表中获得不同名称的模型



我有一个数据库优先的应用程序,其中的表与我的模型具有不同的名称。我的应用程序使用流畅的API工作得很好,直到我添加了一个与另一个模型有一对多关系的模型。然后它开始给我错误:

SqliteException: SQLite Error 1: 'no such column: a0。AuthorAuthorId

示例类如下:

class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public Author Author {get; set; }
}
class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
public ICollection<Book> Books { get; set; }
}

和我的OnModelCreating是-

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>()
.ToTable("tbl_Book")
.HasKey(b => b.BookId);
modelBuilder.Entity<Author>()
.ToTable("tbl_Author")
.HasKey(a => a.AuthorId);
}

我尝试使用.HasOne().WithMany()来指定表之间的关系。

您还没有定义和配置外键属性,因此EF正在寻找具有自己命名约定的外键属性。为了避免这个问题,在Book模型中添加一个外键属性-

class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public int AuthorId { get; set; }
public Author Author {get; set; }
}

,并通过将以下代码添加到OnModelCreating方法来手动配置它-

modelBuilder.Entity<Book>()
.HasOne(p=> p.Author)
.WithMany(p=> p.Books)
.HasForeignKey(p=> p.AuthorId);

最新更新