使用DTO保持干燥

本文关键字:DTO 使用 | 更新日期: 2023-09-27 18:31:57

目前我正在为 FreeRADIUS 创建一个 Web 界面。它只是一个小应用程序,用于简化 Shell 和 SQL 懒惰同事的突变。我为数据库创建了一个实体框架模型,并希望使用外观模式对其进行封装。所以我创建了一个名为 Account 的 DTO 类。它存储从三个不同的表聚合的数据。这是帐户.cs的样子:

public class Account
{
    public int? Id { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string GroupName { get; set; }
    public string IpAddress { get; set; }
    public string Route { get; set; }
}

这是我组装并返回单个帐户-DTO 的方法。

Account Get(string userName)
{
    // Get the values from the database.
    var check = _entities.Checks.Single(x => x.UserName == userName);
    var userGroup = _entities.UserGroups.Single(x => x.UserName == userName);
    var ipReply = _entities.Replies.Single(x => x.UserName == userName && x.Attribute == "Framed-IP-Address");
    var routeReply = _entities.Replies.Single(x => x.UserName == userName && x.Attribute == "Framed-Route");
    // Populate the DTO
    var account = new Account
    {
        UserName = check.UserName,
        Password = check.Value,
        GroupName = userGroup.GroupName
    };
    if (ipReply != null) account.IpAddress = ipReply.Value;
    if (routeReply != null) account.Route = routeReply.Value;
    return account;
}

这是通过用户提交的帐户-DTO 更新数据库的方法

void Update(Account account)
{
    // Get the values from the database. Again.
    var check = _entities.Checks.Single(x => x.UserName == account.UserName);
    var userGroup = _entities.UserGroups.Single(x => x.UserName == account.UserName);
    var ipReply = _entities.Replies.Single(x => x.UserName == account.UserName && x.Attribute == "Framed-IP-Address");
    var routeReply = _entities.Replies.Single(x => x.UserName == account.UserName && x.Attribute == "Framed-Route");
    // Update the possible attributes
    check.Value = account.Password;
    userGroup.GroupName = account.GroupName;
    ipReply.Value = account.IpAddress;
    routeReply.Value = account.Route;
    _entities.SaveChanges();
}

如您所见,我使用完全相同的代码从数据库中检索数据。我怎样才能干掉这段代码?

使用DTO保持干燥

为什么不简单地将共享代码提取到本地类

class AcccountFieldsByName {
// check, userGroup, ipReply, routeReply
    static AcccountFieldsByName Read(... _entities, string userName)    
    {
    return new AcccountFieldsByName {
        check = _entities.Checks.Single(x => x.UserName == userName),
        userGroup = _entities.UserGroups.Single(x => x.UserName == userName),
        ipReply = _entities.Replies.Single(x => x.UserName == userName && x.Attribute == "Framed-IP-Address"),
        routeReply = _entities.Replies.Single(x => x.UserName == userName && x.Attribute == "Framed-Route"),
        }
    }
}