0

我正在尝试将来自 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();

我的目标是得到一个OrganizationwhenOrganizationEntity遇到,同样是一个Userfor UserEntity

我已经尝试过.DisableCtorValidation().ConvertUsing()但那些对我的测试没有帮助。

4

1 回答 1

0

根据 github issue 3293的响应,这似乎是不可能的。虽然感觉应该是因为底层提供者,至少在我的情况下是 CosmosDB 提供者,确实支持通过鉴别器进行继承。

也许 AutoMapper 会改进以支持这一点,但现在我需要找出一种解决方法......

我仍然很乐意接受建议:)

于 2020-05-11T17:20:09.387 回答