[英]How to model a relationship in EF Core when using custom table and field names
我正在嘗試使用EF Core對現有MsSQL Db中的兩個表之間的關系進行建模,但是Db的表具有使用自定義表名和列名的表。
即使我使用屬性或FluentAPI指定關系,EF Core也無法建立關系。
我認為問題是因為我有表和列的非常規名稱,並且EF無法正確設置關系。
這是SQL:
CREATE TABLE paid_authors
(
paid_author_id varchar(50) NOT NULL,
[name] varchar(50) NOT NULL
)
CREATE TABLE hardback_books
(
hardback_book_id uniqueidentifier NOT NULL,
paid_author_id varchar(50) NOT NULL,
title varchar(50) NOT NULL
)
INSERT INTO paid_authors VALUES ('duck' ,'Scrooge McDuck')
INSERT INTO hardback_books VALUES (NEWID(), 'duck', 'Duck Tales')
這是C#建模:
[Table("paid_authors")]
public class PaidAuthor
{
[Key]
[Column("paid_author_id")]
public string PaidAuthorId { get; set; }
[Column("name")]
public string Name { get; set; }
public virtual List<HardbackBook> HardbackBooks { get; set; }
}
[Table("hardback_books")]
public class HardbackBook
{
[Key]
[Column("hardback_book_id")]
public Guid HardbackBookId { get; set; }
[Column("title")]
public string Title { get; set; }
[ForeignKey("HardbackBooks")] // This could be wrong!
[Column("paid_author_id")]
public string PaidAuthorId {get; set;}
}
我的代碼:
foreach(var author in context.PaidAuthors.Take(10))
{
// This next line makes it work, but it shouldn’t be needed!
// author.HardbackBooks = context.HardbackBooks.Where(x => x.PaidAuthorId == author.PaidAuthorId).ToList();
Console.WriteLine(author.PaidAuthorId + " - " + author.Name);
Console.WriteLine(author.HardbackBooks.Count);
}
當我運行代碼時,我得到System.NullReferenceException
和author.HardbackBooks
為null。
我已經嘗試過FluentAPI,在父類上指定ForeignKey……但是肯定有些明顯的東西我不見了! 如果可以在此工作,我很樂意切換到FluentAPI。
不用說,我無法更改Db結構... :-(
您不能將集合Navigation Property保留為空,並且在書上應該具有反向Navigation屬性。 就像是:
[Table("paid_authors")]
public class PaidAuthor
{
[Key]
[Column("paid_author_id")]
public string PaidAuthorId { get; set; }
[Column("name")]
public string Name { get; set; }
public virtual List<HardbackBook> HardbackBooks { get; } = new HashSet<HardbackBook>();
}
[Table("hardback_books")]
public class HardbackBook
{
[Key]
[Column("hardback_book_id")]
public Guid HardbackBookId { get; set; }
[Column("title")]
public string Title { get; set; }
public PaidAuthor PaidAuthor { get; set; }
[ForeignKey("PaidAuthor")]
[Column("paid_author_id")]
public string PaidAuthorId { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.