[英]Load navigation properties in generic repository
I have a problem when using AutoMapper and EF Core together to map navigation properties from the model to the DTO.将 AutoMapper 和 EF Core 一起使用到从 model 到 DTO 的 map 导航属性时遇到问题。 My EF classes are:
我的 EF 课程是:
public class Meal
{
public DateTime Day { get; set; }
public MealType MealType { get; set; }
public int MealId { get; set; }
}
public class MealType
{
public string Name { get; set; }
public int MealTypeId { get; set; }
}
And the corresponding DTO classes:以及相应的 DTO 类:
public class ExistingMealDto
{
public DateTime Day { get; set; }
public ExistingMealTypeDto MealType { get; set; }
public int MealId { get; set; }
public string MealTypeName { get; set; }
}
public class ExistingMealTypeDto
{
public string Name { get; set; }
public int MealTypeId { get; set; }
}
This is my AutoMapper mapping:这是我的 AutoMapper 映射:
config.CreateMap<DataLayer.EfClasses.MealType, ExistingMealTypeDto>();
config.CreateMap<DataLayer.EfClasses.Meal, ExistingMealDto>()
.ForMember(x => x.MealType, x => x.MapFrom(x=>x.MealType))
.ForMember(x => x.MealTypeName, x => x.MapFrom(y => y.MealType.Name));
I'm loading the data within a generic method that looks like this:我在一个看起来像这样的通用方法中加载数据:
public IEnumerable<TDtoOut> GetAllAsDto<TIn, TDtoOut>()
where TIn : class
{
var allEntities = DbContext.Set<TIn>();
return Mapper.Map<IEnumerable<TDtoOut>>(allEntities);
}
When calling this code, all Meal
instances are loaded from the database and MealId
and Day
are filled correctly.调用此代码时,所有
Meal
实例均从数据库中加载,并且MealId
和Day
已正确填写。 However, MealType
is null
and therefore ExistingMealDto.MealType
is null
as well.但是,
MealType
是null
,因此ExistingMealDto.MealType
也是null
。 I can work around this problem by explicitly calling DbContext.MealTypes.ToList()
, but since the method should be generic for TIn
, this is not a production solution.我可以通过显式调用
DbContext.MealTypes.ToList()
来解决这个问题,但由于该方法对于TIn
应该是通用的,因此这不是生产解决方案。
How can I solve this issue?我该如何解决这个问题? Thanks!
谢谢!
For getting the related data in generic method, you can judge the Type of the passed type.对于泛型方法中获取相关数据,可以判断传入类型的类型。 The following is a test demo, you could refer to:
下面是一个测试demo,可以参考:
public IEnumerable<TIn> GetAllAsDto<TIn>()
where TIn : class
{
Type typeParameterType = typeof(TIn);
if (typeParameterType == typeof(User))
{
var Entities = _context.Set<User>().Include(u=>u.Orders);
return (IEnumerable<TIn>)Entities;
}
else
{
var allEntities = _context.Set<TIn>();
return allEntities;
}
}
public void Test()
{
var data = GetAllAsDto<User>();
var data1 = GetAllAsDto<Status>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.