我正在尝试将来自 CosmosDB 支持的 EF Core 的许多实体映射到实现接口的一组等效的具体类型。为简单起见,在下面的示例中,我刚刚将其剥离为List<T>
。
当我运行代码时,我收到一个关于IAccount
没有默认构造函数的异常。
IAccount"没有默认构造函数(参数"类型"(">
错误发生在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();
我的目标是在遇到OrganizationEntity
时获得Organization
,同样,UserEntity
的User
。
我已经尝试了.DisableCtorValidation()
和.ConvertUsing()
但这些对我的测试没有帮助。
根据 github 问题 3293 的响应,这似乎是不可能的。 虽然感觉应该是因为基础提供程序(至少在我的情况下是 CosmosDB 提供程序(确实支持通过鉴别器进行继承。
也许自动映射器会改进以支持这一点,但现在我需要找出一种解决方法......
我很乐意接受建议:)