[英]In AutoMapper how does one project from an abstract base class to an interface
我正在嘗試 map 一些實體,這些實體來自 CosmosDB 支持的 EF Core 到實現接口的等效具體類型集。 為簡單起見,在下面的示例中,我只是將其簡化為List<T>
。
當我運行我的代碼時,我得到一個關於IAccount
沒有默認構造函數的異常。
`IAccount' 沒有默認構造函數(參數 'type')'
錯誤發生在var query = mapper.ProjectTo<IAccount>(repo);
. 我已經嘗試了所有我能想到的配置組合,但我被卡住了。
我當前的版本如下,它是從我原來的類中剝離出來的。 這就是AccountBase
存在的原因,這在示例中並不明顯。
源類型
public abstract class AccountEntity
{
public Guid Id { get; set; }
public abstract string Name { get; set; }
}
public class UserEntity : AccountEntity
{
public string Username { get; set; } = null!;
public string Email { get; set; } = null!;
public string FirstName { get; set; } = null!;
public string LastName { get; set; } = null!;
public override string Name { get; set; } = null!;
}
public class OrganizationEntity : AccountEntity
{
public override string Name { get; set; } = null!;
public IEnumerable<string> Industries { get; set; } = null!;
public string? Website { get; set; }
}
目的地類型
public interface IAccount
{
Guid Id { get; }
string Name { get; }
}
public abstract class AccountBase : IAccount
{
public Guid Id { get; set; }
public string Name { get; set; } = null!;
}
public class User : AccountBase
{
public string Username { get; set; } = null!;
public string Email { get; set; } = null!;
public string FirstName { get; set; } = null!;
public string LastName { get; set; } = null!;
}
public class Organization : AccountBase
{
public IEnumerable<string> Industries { get; } = null!;
public string? Website { get; set; }
}
測試
var config = new MapperConfiguration(c =>
{
c.CreateMap<AccountEntity, IAccount>()
.IncludeAllDerived();
c.CreateMap<UserEntity, IAccount>()
.As<User>();
c.CreateMap<UserEntity, User>();
c.CreateMap<OrganizationEntity, IAccount>()
.As<Organization>();
c.CreateMap<OrganizationEntity, Organization>();
});
config.AssertConfigurationIsValid();
var mapper = config.CreateMapper();
var repo = new List<AccountEntity>()
{
new UserEntity()
{
Id = Guid.NewGuid(),
FirstName = "First",
LastName = "User"
},
new OrganizationEntity()
{
Id = Guid.NewGuid(),
Industries = new [] { "SPACETRAVEL" },
Name = "Org 1"
}
}.AsQueryable();
var queryProjection = mapper.ProjectTo<IAccount>(repo);
var results = queryProjection.ToList();
我的目標是在遇到Organization
時獲得一個OrganizationEntity
,同樣獲得一個UserEntity
的User
。
我已經嘗試過.DisableCtorValidation()
和.ConvertUsing()
但這些對我的測試沒有幫助。
根據 github 問題3293的響應,這似乎是不可能的。 雖然感覺應該是因為底層提供者,至少在我的情況下是 CosmosDB 提供者,確實通過鑒別器支持 inheritance。
也許 AutoMapper 會改進以支持這一點,但現在我需要找出一種解決方法......
我仍然很樂意接受建議:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.