目前我正在为FreeRADIUS创建一个网络界面。它只是一个小应用程序,用于简化 Shell 和 SQL 懒惰的同事的突变。我为数据库创建了一个实体框架模型,并希望使用外观模式来封装它。所以我创建了一个名为Account的 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();
}
如您所见,我使用完全相同的代码从数据库中检索数据。我怎样才能干掉这段代码?