[英]EF Core: How to have models with different names from the tables
我有一個數據庫優先的應用程序,其中的表名稱與我的模型不同。 我的應用程序使用流暢的 API 運行良好,直到我添加了一個與另一個 model 具有一對多關系的 model。 然后它開始給我錯誤:
SqliteException:SQLite 錯誤 1:'沒有這樣的列: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
model 中添加外鍵屬性 -
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.