我正在尝试将来自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; }
}
Test
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
,同样为User
获得一个UserEntity
。
我尝试过.DisableCtorValidation()
和.ConvertUsing()
,但对我的测试没有帮助。
根据github问题3293的答复,似乎不可能。尽管感觉应该是因为底层提供程序(至少在我的情况下是CosmosDB提供程序)确实支持通过Discriminator继承。
也许AutoMapper将有所改进以支持此功能,但现在我需要找出解决方法...
我仍然很乐意接受建议:)