Stay DRY with DTO

I am currently creating a web interface for FreeRADIUS . This is just a small mutation simplification application for Shell and SQL-lazy employees. I have created an Entity Framework model for a database and want to encapsulate it using a facade template. So I created a DTO class called Account . It stores data aggregated from three different tables. This is what Account.cs looks like:

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; } } 

This is the method that I collect and return one DTO account.

 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; } 

And this is a method of updating a database using a custom DTO account

 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(); } 

As you can see, I use the same code to retrieve data from the database. How can I dry this code?

+6
source share
1 answer

Why not just extract the generic code into a local class

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

Source: https://habr.com/ru/post/913955/


All Articles