Automapper:如何将IList映射到EntityCollection [英] Automapper: How to map IList to EntityCollection
问题描述
我正在使用Automapper v1.1,因为我正在使用.NET 3.5以及使用Entity Framework。
I am using Automapper v1.1, since I am using .NET 3.5 as well as using Entity Framework.
我正在尝试将ViewModel映射到模型但不断出现错误。我有以下样本类:
I'm trying to map a ViewModel to Model but keep running into errors. I have the below sample classes:
OrderViewModel
public class OrderViewModel{
public string OrderNo { get; set; }
public IList<OrderItem> DisplayItems { get; set; }
public OrderViewModel(){
DisplayItems = new List<OrderItem>();
}
}
订单(注意:这个类是由EF自动生成的)
public class Order{
public string OrderNo { get; set; }
public EntityCollection<OrderItem> OrderItems { get; set; }
...
}
OrderItem(注意:此类由EF自动生成)
public class OrderItem{
public string Name { get; set; }
public int Quantity { get; set; }
public int Price { get; set; }
...
}
我的功能
public void MyFunction(OrderViewModel source){
//initialize mapping
Mapper.CreateMap<OrderViewModel, Order>().ForMember(dest => dest.OrderItems, opt => opt.MapFrom(src => src.DisplayItems));
//map viewmodel to model
var model = Mapper.Map<OrderViewModel, Order>(source);
//does not reach this point
}
我试图跟踪,当它尝试将DisplayItem映射到OrderItems属性时停止。我收到以下错误:
When I tried to trace, it is stopping when it tries to map the DisplayItems to the OrderItems property. I am receiving the following error regarding it:
System.InvalidOperationException:请求的操作现在允许
当相关的所有者为空。 RelatedEnd使用默认构造函数创建
的对象只能在序列化期间用作
容器。
System.InvalidOperationException: Requested operation is now allowed when the owner of this RelatedEnd is null. RelatedEnd objects that were created with the default constructor should only be used as a container during serialization.
我究竟做错了什么?使用Automapper将IList映射到EntityCollection的方法是什么?我正在这样做,因为我不想写一个迭代代码,只是将项目从一个集合复制/传输到另一个集合。
What am I doing wrong? What's the correct way to map an IList to an EntityCollection using Automapper? I am doing this because I do not want to write an iterative code just to copy / transfer items from one collection to the other.
推荐答案
p>我认为这基本上是因为你明确地从列表
创建一个 EntityCollection
类型的地图 - 从什么我已经看到似乎人们最终反复地做这个(我还没有看到直接转换/转换)。但是,如果你想要这样做,这种方法似乎可以完成工作。
I think it's basically because you're explicitly creating the map from a List
to a EntityCollection
type - from what I've seen it seems people end up doing this iteratively (I haven't seen a direct cast/conversion yet). But if you want it to work, this approach seems to get the job done.
快速搜索可以通过使用更多或更少的自定义映射器代码,具有迭代。 这是一篇文章一些例子。
Doing a quick search you can find some examples where this is managed by using more or less custom mapper code, with iteration. Here's a post with a few examples.
Here's another one that expresses it more clearly.
祝你好运!
这篇关于Automapper:如何将IList映射到EntityCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!