如何在域模型上使用选择

时间:2019-08-27 17:12:21

标签: c# asp.net-core entity-framework-core domain-driven-design

我有一些实体,这些实体可以通过自动映射器映射到域模型,并作为Iqueryable从服务中返回。如何在它们上使用.select或使用automapper projectTo来将它们映射到视图模型,因为在尝试时会抛出错误IAsyncEnumerable不能用于域模型内部导航属性上的IEnumerable类型的参数?

class HomeDomainModel
{
    public string Id { get; set; }

    public ICollection<HumanDomainModel> Humans { get; set; }
}
class HumanDomainModel
{ 
    public string Id { get; set; }
}
class HomaEntity
{
    public string Id { get; set; }

    public ICollection<HumanEntity> Humans { get; set; }
}
class HumanEntity 
{
    public string Id { get; set; }
}
// IQueryable<HomeEntity>
var homeEntities = homeEntities.GetAll();

// IQueryable<HomeDomainModel>
var homeDomainModels = humanEntity.ProjectTo<HomeDomainModel>();

// Here it throws the exception
var homeViewModel = homeDomainModels.Select(hdm => new HomeViewModel()
    {
        Id = hdm.Id,
        HumansCount = hdm.Humans.Count()
    }).ToArrayAsync();

1 个答案:

答案 0 :(得分:0)

如果要将ButtonColorView映射到ICollection<HumanEntity> Humans { get; set; },可以尝试以下代码:

  1. HumansCount

    Profile
  2. 用例

    public class ModelProfile: Profile
    {
        public ModelProfile()
        {
            CreateMap<HomaEntity, HomeViewModel>()
                .ForMember(dest => dest.HumansCount, opt => opt.MapFrom(src => src.Humans.Count));           
        }
    }
    

更新

对于EF Core,它在LINQ查询中具有混合客户端/数据库评估的概念。对于您的代码,var humanEntity = new List<HomaEntity> { new HomaEntity{ Id = "T1", Humans = new List<HumanEntity>(){ new HumanEntity{ Id = "H1"}, } }, new HomaEntity{ Id = "TT1", Humans = new List<HumanEntity>(){ new HumanEntity{ Id = "HH1"}, new HumanEntity{ Id = "HH2"}, } }, new HomaEntity{ Id = "TT1", Humans = new List<HumanEntity>(){ new HumanEntity{ Id = "HHH1"}, new HumanEntity{ Id = "HHH2"}, new HumanEntity{ Id = "HHH3"} } } }; // Here it throws the exception var homeViewModels = _mapper.Map<List<HomeViewModel>>(humanEntity); 将在客户端运行,而HumansCount = hdm.Humans.Count()将作为服务器端或异步运行。

有两种选择适合您:

  • ToArrayAsync()更改为.ToArrayAsync()
  • 对于此限制,此问题已在EF Core 3.0中修复,如果您需要使用.ToArray(),则可以尝试使用ef core 3.0(例如,版本{)将.net core 2.2项目迁移到.net core 3.0。 {1}}