gpt4 book ai didi

c# - 在没有重复代码的情况下将实体映射到 DTO

转载 作者:太空宇宙 更新时间:2023-11-03 10:39:11 24 4
gpt4 key购买 nike

我正在努力解决这个问题,因为我在 N 层应用程序中使用 Entity Framework (6)。由于存储库中的数据(包含与数据库的所有通信)应该在更高层(UI、服务等)中使用,因此我需要将其映射到 DTO。

在数据库中,有相当多的多对多关系在进行,因此数据结构可能/将在应用程序生命周期的某个地方变得复杂。我偶然发现的是,我在编写存储库方法时重复了完全相同的代码。我的 FirmRepository 就是一个例子,它包含一个 GetAll() 方法和 GetById(int firmId) 方法。

GetById(int firmId) 方法中,我有以下代码(不完整,因为有很多更多的关系需要映射到 DTO):

public DTO.Firm GetById(int id)
{
// Return result
var result = new DTO.Firm();

try
{
// Database connection
using (var ctx = new MyEntities())
{
// Get the firm from the database
var firm = (from f in ctx.Firms
where f.ID == id
select f).FirstOrDefault();

// If a firm was found, start mapping to DTO object
if (firm != null)
{
result.Address = firm.Address;
result.Address2 = firm.Address2;
result.VAT = firm.VAT;
result.Email = firm.Email;

// Map Zipcode and City
result.City = new DTO.City()
{
CityName = firm.City.City1,
ZipCode = firm.City.ZipCode
};

// Map ISO code and country
result.Country = new DTO.Country()
{
CountryName = firm.Country.Country1,
ISO = firm.Country.ISO
};

// Check if this firm has any exclusive parameters
if (firm.ExclusiveParameterType_Product_Firm.Any())
{
var exclusiveParamsList = new List<DTO.ExclusiveParameterType>();

// Map Exclusive parameter types
foreach (var param in firm.ExclusiveParameterType_Product_Firm)
{
// Check if the exclusive parameter type isn't null before proceeding
if (param.ExclusiveParameterType != null)
{
// Create a new exclusive parameter type DTO
var exclusiveParameter = new DTO.ExclusiveParameterType()
{
ID = param.ExclusiveParameterType.ID,
Description = param.ExclusiveParameterType.Description,
Name = param.ExclusiveParameterType.Name
};

// Add the new DTO to the list
exclusiveParamsList.Add(exclusiveParameter);
}
}

// A lot more objects to map....

// Set the list on the result object
result.ExclusiveParameterTypes = exclusiveParamsList;
}
}
}

// Return DTO
return result;
}
catch (Exception e)
{
// Log exception
Logging.Instance.Error(e);

// Simply return null
return null;
}
}

这只是一种方法。 GetAll() 方法将具有完全相同 的映射逻辑,这会导致代码重复。此外,当添加更多方法时,即 FindSearch 方法,需要再次复制相同的映射。当然,这并不理想。

我已经阅读了很多关于可以将实体映射到 DTO 或从 DTO 映射实体的著名的 AutoMapper 框架,但是由于我有这些多对多关系,所以很快就觉得 AutoMapper 配置代码很臃肿。我也读过这篇文章,这在我看来很有意义:http://rogeralsing.com/2013/12/01/why-mapping-dtos-to-entities-using-automapper-and-entityframework-is-horrible/

有没有其他方法可以避免一遍又一遍地复制/粘贴相同的代码?

提前致谢!

最佳答案

你可以像这样在实体公司(DB.Firm)上做一个扩展方法,

public static class Extensions
{
public static DTO.Firm ToDto(this DB.Firm firm)
{
var result = new DTO.Firm();
result.Address = firm.Address;
result.Address2 = firm.Address2;
//...

return result;
}
}

然后您可以在代码中的任何位置转换 DB.Firm 对象,例如 firm.ToDto();

关于c# - 在没有重复代码的情况下将实体映射到 DTO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26126551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com