用DTO保持干爽

时间:2012-04-23 15:50:23

标签: c# entity-framework oop dry

目前我正在为FreeRADIUS创建一个网络界面。它只是一个小应用程序,用于简化Shell和SQL-lazy同事的突变。我为数据库创建了一个Entity Framework模型,并希望使用facade模式对其进行封装。所以我创建了一个名为帐户的DTO课程。它存储从三个不同表聚合的数据。这就是Account.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; }
}

这是我组装并返回单个Account-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;
}

这是通过用户提交的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();
}

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

1 个答案:

答案 0 :(得分:1)

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

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"),
        }
    }
}