自动映射器,用于复制 EF 连接的对象,而无需行和行代码



这有点长,所以给自己喝杯咖啡(其他质量的酒可用(。

为了尽可能少地编写代码,请保持我的应用程序简单、可测试、可维护和干净,并快速启用应用程序。

我正在使用我编写的一种非常简单的方法从 MVC 对象复制到 EF 对象,以便在我拥有具有大量属性的对象时节省我编写大量代码。事实上,我不在乎对象是什么或它有多少属性。我只想复制它,而无需在地图或某处准备大量代码。

请不要从视图模型和所有这些开始,并引用我Microsoft的大书。我一直在寻求我的同行和社区对AutoMapper的一些建议 这里的例子很简单,所以你可以看到我的意思。

我不想做的,我已经看到了很多,是:-

item ... //the original item populated from somewhere, MVC database, who cares, its got stuff in it
Item newItem = new Item();
newItem.prop1 = item.prop1;
newItem.prop2 = item.prop2;
newItem.prop3 = item.prop3;
newItem.prop4 = item.prop4;
//... you get the idea

甚至这个...

Item newItem = new Item {  
prop1 = item.prop1,
prop2 = item.prop2,
prop3 = item.prop3,
prop4 = item.prop4,
//... you get the idea
}

所以我想出了这个。一个名为CopyObject的函数,它完全执行了我想要它做的事情,所以我不必关心任何对象或它有多少属性,我在我需要的任何地方编写一行代码来为我完成所有工作。请参阅下面的示例

//show the item in a view, typically a bootstrap popup dialog
public IActionResult EditItem(int ID)
{
Item item = _dbContext.Items.Where(i => i.ID == ID).FirstOrDefault();
if (item == null)
item = new Item { ... property defaults ... };
return View(item);
}
//save the item from the view
[HttpPost]
public JsonResult EditItem(Item item)
{
Item newItem = _dbContext.Item.Where(i => item.ID).FirstOrDefault();
if (newItem == null)
{
newItem = newItem {... property defaults ... };
_dbContext.Items.Add(newItem);
}
//here is the fun part
CopyObject(item, newItem, ...ignore some properties);
_dbContext.SaveChanges();
return new JsonResult( new { result = "success", message = "Updated" });
}

CopyObject是我的函数,它没有什么聪明的,除了它使用反射将属性从一个对象复制到另一个 (EF( 对象而不会丢失与 EF 的连接。CopyObject 如下所示(如下所示(。我不会让你厌烦这个实现,但简单地说,它使用反射来复制任何两个对象之间的属性。

目前它只从顶层复制,因为这就是我现在需要它做的全部工作,但让它复制东西的层次结构并不是一件大事。

它实际上并不关心对象类型是否匹配,也不关心属性类型是否匹配。它只关心 if 在每个对象上找到具有相同名称的属性,然后它会尝试复制值。还可以指定不复制的属性。

/// <summary>
/// Copies the values of the properties from one object to another object with the same properties if they exist.
/// This will try to copy from any two objects whether they are the same object type or not
/// </summary>
/// <param name="CopyFrom">The object to copy property data from</param>
/// <param name="CopyTo">The object to copy property data to</param>
/// <param name="DontCopy">A (string) list field names not to be copied</param>
/// <returns>True if at least one property was copied, otherwise false</returns>
public bool CopyObjects(object CopyFrom, object CopyTo, params string[] DontCopy) {...}

我的代码没有任何问题,它以我需要的方式完美运行。当我开始一个新项目时,无论任何对象有多少属性,我都没有任何额外的工作要做。我只是导入那个

无论如何,因为我没有发表或任何类型的权威,我的代码变得不受欢迎。有人告诉我AutoMapper可以做同样的事情,但我似乎做不到。我总是得到一个断开连接的对象,然后我必须做一些愚蠢的事情才能将其返回到 EF 并最终返回到数据库中。

所以我的问题是。如何在没有大量代码的情况下使用自动映射器实现同样的事情?请记住,我的目标不是在准备或行中编写大量代码。

> AutoMapper 可以使用以下代码忽略属性(例如以下示例中的Name(

public class MyProfile : Profile
{
public MyProfile ()
{
CreateMap<Item, Item>().ForMember(x => x.Name, opt => opt.Ignore()) ;
}
}

您的操作:

var newItem = _mapper.Map<Item, Item>(item);

忽略使用自动映射器映射一个属性

https://medium.com/ps-its-huuti/how-to-get-started-with-automapper-and-asp-net-core-2-ecac60ef523f

最新更新