【发布时间】:2019-08-05 15:40:42
【问题描述】:
我有这个简单的课程
public class Store {
public int Id { get; set; }
//Other properties
[JsonIgnore]
public ICollection<Product> Products { get; set; }
}
还有我的 DTO
public class StoreDetails {
public int Id { get; set; }
//Other properties
public ICollection<Product> Products { get; set; }
}
还有我的Product 班级:
public class Product {
public int? Id { get; set; }
//Other properties
public ICollection<ProductAttribute> ProductAttributes { get; set; }
}
我的映射看起来像这样:
var storeDetails = await _context.Stores
.Include(s => s.Products)
.ThenInclude(p => p.ProductAttributes)
.ProjectTo<StoreDetails>(new MapperConfiguration(c => c.CreateProfile("TEST", e => {
e.CreateMap<Store, StoreDetails>();
})))
.SingleOrDefaultAsync(p => p.Id == id);
Store 对象中的一切看起来都很好,但在 StoreDetails 中,ProductAttributes 每次都是 null。
为什么 AutoMapper 不使用 ProjectTo 映射二级导航属性?
注意:我使用的是 AutoMapper 8.1.1。
【问题讨论】:
-
您不需要包含在 ProjectTo 中。
-
如果我没看错的话,
Product对两者来说是同一个类,所以不需要对其执行任何映射。您是否尝试在不使用ThenInclude(p => p.ProductAttributes)的情况下运行它? -
@SSchulze 没有
ThenInclude的结果相同 -
@LucianBargaoanu 有没有办法(我猜答案是否定的)强制对相等的源和目标(元素)类型进行投影?看起来
AssignableExpressionBinder和EnumerableExpressionBinder几乎不会强制投影源表达式。 -
可能没有
ToList,因为AssignableExpressionBinder在EnumerableExpressionBinder之前。更改顺序会完成您想要的,但是,正如我所说,没有它它对我有用。
标签: c# asp.net-core automapper