[英]EF Core One To Many Include
我在我的數據庫中使用 EF-CORE 在 ASP.NET Core MVC 網站上工作。
我有一個Doc
表和一個Signature
表:
Doc
可以有多個Signatures
Signature
只能在Doc
。這是我的代碼優先實體模型:
public class Doc
{
[Key]
public int DocID { get; set; }
[Required]
public int DocTypeID { get; set; }
[ForeignKey("DocTypeID")]
public virtual DocType DocType { get; set; }
[Required]
public int Version { get; set; }
[Required]
public Byte[] Data { get; set; }
[ForeignKey("DocID")]
public List<Signature> Signatures { get; set; }
}
public class Signature
{
//FK ITPolicyVersion
[Key]
public int DocID { get; set; }
[ForeignKey("DocID")]
public virtual Doc Doc { get; set; }
//FK EmployeeID
[Key]
public int EmployeeID { get; set; }
[ForeignKey("EmployeeID")]
public virtual Employee Employee { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Signature Date")]
public DateTime? SignatureDate { get; set; }
public String Value { get; set; }
}
但是當我使用這個請求時:
_applicationDBContext.Doc
.Include(d => d.DocType)
.Include(d => d.Signatures)
.OrderBy(d => d.DocType)
.ToList();
d.Signatures
始終為空,我不知道為什么。
這是我在 SQL 中嘗試執行的操作:
SELECT * FROM Doc d
JOIN DocType dt ON dt.DocTypeID = d.DocTypeID
JOIN Signature s ON s.DocID = d.DocID
JOIN Employee e ON e.EmployeeID = s.EmployeeID
這在 SQL 中運行良好,但不適用於 LINQ
編輯
這項工作:
List<Doc> docs = _applicationDBContext.Doc
.Include(d => d.Signatures)
.ThenInclude(s => s.Employee)
.Include(d => d.DocType)
.ToList();
但不是這個:
List<Doc> docs = _applicationDBContext.Doc
.Include(d => d.Signatures)
.ThenInclude(s => s.Employee)
.Include(d => d.DocType)
.OrderBy(d => d.DocType)
.ToList();
Signature
為空
如何按DocType
訂購此列表?
事實上,orderby 上有一個錯誤,但它沒有拋出:DocType 是另一個表,沒有實現 IComparable,所以我只是像這樣更改請求:
List<Doc> docs = _applicationDBContext.Doc
.Include(d => d.Signatures)
.ThenInclude(s=>s.Employee)
.Include(d => d.DocType)
.OrderBy(d => d.DocType.Name)
.ToList();
它完美地工作。
在您的 DbContext 的 OnModelCreating 中,您是否放置了 Doc 和 Signature 的關系? 像這樣:
modelBuilder.Entity<Signature>().HasOne(m => m.Doc).WithMany(m => m.Signature).HasForeignKey(m => m.DocID);
您應該能夠簡化為這樣的事情。
請記住,很多事情都是按慣例工作的,因此命名很重要(例如,實體框架會自動獲取實體鍵的 Id)
如果您在“子”對象上具有向后導航屬性,則需要外鍵屬性和 id 屬性或使用 Fluent API。
public class Doc
{
public int Id { get; set; }
public DocType DocType { get; set; }
[Required]
public int Version { get; set; }
[Required]
public Byte[] Data { get; set; }
public List<Signature> Signatures { get; set; }
}
public class Signature {
public int Id { get; set; }
//backwards navigation
public int DocForeignKey {get;set;}
[ForeignKey("DocForeignKey")]
public Doc Doc { get; set; }
public Employee Employee { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Signature Date")]
public DateTime? SignatureDate { get; set; }
public String Value { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.