[英]Entity Framework - include ComplexType
我在EF Core 2.0中有一個實體類:
public class Component : BaseModel
{
[Required]
public string Name { get; set}
public virtual ICollection<ComponentInstance> ComponentInstances { get; set; }
public virtual Title Title {get ; set;}
}
和另一個ComplexType
類:
[ComplexType]
public class Title
{
public string Text { get; set; }
public string Color { get; set; }
public string BackgroundColor { get; set; }
}
運行此代碼:
var component = _dbContext.Company
.Where(x => x.Id == componentId)
.Include(x => x.Title)
.FirstOrDefault();
引發異常:
屬性“標題”不是實體類型“組件”的導航屬性。 “ include(string)”方法只能與“。”一起使用。 導航屬性名稱的分隔列表。
如果您仍在掙扎,則需要在課程中添加[ForeignKey("")]
。 像這樣:
public class Component : BaseModel
{
[Required]
public string Name { get; set}
public virtual ICollection<ComponentInstance> ComponentInstances { get; set; }
[ForeignKey("Title")]
public Title Title {get ; set;}
}
最可能的問題是,在您的Component
類中, Title
屬性未標記為virtual
。
如果不是,則virtual
實體框架無法override
它,然后將其忽略,並且不會將其視為具有上下文的實體。
現在,即使將其標記為虛擬,也不一定意味着實體框架會將其識別為實體,因此在這種情況下,您需要指定與Entity Framework的Fluent API的關系。
如果Component類的關系對於實體框架是清楚的,則基於Convention over Configuration ,則無需明確聲明與流利API的關系。
顯然,您的類也需要繼承自DbContext
類的DbSet<Component>
和DbSet<Title>
屬性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.