![](/img/trans.png)
[英]How do I add an entity model to a .Net Core ClassLibrary using Entity Framework Core in Visual Studio 2019?
[英].Net Core & Entity Framework Core - access properties of subclass in model using Table Per Hierarchy
我是.Net核心和實體框架的新手。 我正在一個.Net Core項目中,該項目具有使用“代碼優先”方法創建的數據庫。 模型中存在以下繼承結構(偽代碼):
public abstract class LegalEntity{
// common properties
public virtual LegalEntityDto ToDto()
{
return null;
}
}
public class Person : LegalEntity
{
public string FirstName {get; private set;}
public DateTime? DateOfBirth {get; private set;}
// ... Other person-specific properties.
public new PersonDto ToDto()
{
return new PersonDto
{
{
Firstname = Firstname,
DateOfBirth = DateOfBirth
// ...
};
}
public class Company : LegalEntity
{
public string Abn {get; private set;}
public string CompanyName {get; private set;}
// ... Other company-specific properties.
public new CompanyDto ToDto()
{
return new CompanyDto
{
{
Abn = Abn,
CompanyName = CompanyName
// ...
};
}
(Dto遵循相同的繼承結構,即PersonDto和CompanyDto從LegalEntityDto繼承)。
在SQL數據庫中,有一個LegalEntity表,該表在Table Per Hierarchy實現的后面包含每個LegalEntity,Person和Company屬性的列,以及Discriminator列(該列由C#模型類名稱填充)。
我有一個方法應該返回LegalEntityDto的列表,該列表可以是Person和/或Company對象的組合。 代碼類似於以下內容(更多偽代碼):
public List<LegalEntityDto> GetImportantEntitiesForAccount(int accountNumber){
var account = DbContext.Account.FirstOrDefault(p => p.accountNumber == accountNumber);
if (account == null){
throw AccountNotFoundException("Account not found for accountNumber: " + accountNumber);
}
var importantEntities = account.ImportantEntities;
var dtos = importantEntities.Select(i => i.ToDto()).ToList();
return dtos;
}
我的問題是對每個“ importantEntity”的ToDto()
調用,都調用了抽象的LegalEntity ToDto()方法(該方法返回null)。 在運行時檢查的集合時,我可以看到importantEntities
該對象包含任一的屬性Person
或Company
,並且被示出為一個Castle.Proxies.PersonProxy
或Castle.Proxies.CompanyProxy
類型。
我的問題是,如何訪問運行時顯然可用的Person或Company屬性,或者以某種方式調用ToDto()的Person或Company實現?
正如Ivan Stoev所說,解決方案是使基本ToDto()方法抽象並在Person和Company實現中重寫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.