将Entity Framework对象转换为另一个实体框架对象

时间:2016-06-10 02:57:11

标签: c# .net entity-framework

我有两张桌子"产品"和" Product_Recovery"。它们具有相同的结构。

所以,我想将产品实体对象转换为Product_Recovery对象,反之亦然,但我收到错误:

  

无法转换为' MyProject.Objects.Product'到' MyProject.Objects.Product_Recovery'

有没有简单的方法可以做到这一点?

1 个答案:

答案 0 :(得分:3)

不,你不能将一个对象转换为另一个对象,除非另一个对象派生。 C#应该如何知道类是一样的?但是,您可以使用Product库从Product_Recovery转换为AutoMapper,这样可以通过使用反射来简化这一过程。

查看Project PageGetting Started,并在您准备好使用时Nuget安装。

最简单的使用方法示例(从“入门”中复制):

// execute this somewhere in your program construction 
// only once to generate the required mappings
Mapper.Initialize(cfg => cfg.CreateMap<Product, Product_Recovery>());

// execute this to transform from one to another:
Product dto = Mapper.Map<Product_Recovery>(productInstance);
相关问题