-1

Follow my code (just the demo doubt), this code I have a method in my service that receives a list of users and saves, the only rule of business is to check if the User already exists.

There is also a log of that call, the idea is simple it will work quiet, My doubt is, I'm doing 2 SaveChanges () and it seems to be wrong, how could I improve this code? I thought I would call only once in CreateUser method (), but that would be dangerous, because there could be repetitions of CPF in the "Users" list, I would have to create a validate this list, but wanted to avoid this, as it seems to me least of the problems, I think I'm erring on the solution architecture.

public class Service : IMyService {
   private UserEntitiescontext context = new UserEntities();  

   // Service method

   public bool CreateUser(List<User> users) {
        foreach (var user in users) {
            new UserDomain().createUser(context, user);

            new LogDomain().createLog(context, new Log { UserCreated = user .... });   
       }   
   }      
}

public class UserDomain() {

   private createUser(UserEntities context, User user) {

          if (context.Users.Where(f=>f.CPF == user.CPF).FirstOrDefault() != null) {
              context.Attach(user);    
              context.SaveChanges();                  
          }   
   }  
}

public class LogDomain() {

   private createLog(UserEntities context, Log log) {   
             context.Attach(log);   
             context.SaveChanges(); 
   }    
}
Lee O.
  • 3,212
  • 2
  • 26
  • 36
Junior
  • 199
  • 1
  • 9
  • It's really difficult to tell what you're asking here, and it seems this is a more likely candidate for http://codereview.stackexchange.com/, but it seems like you might be looking for transactions. See http://stackoverflow.com/questions/867643/how-to-use-transactions-with-a-datacontext – Preston Guillot Jan 23 '14 at 04:06

2 Answers2

0
   public bool CreateUser(List<User> users) {
        foreach (var user in users) {
            new UserDomain().createUser(context, user);   
            new LogDomain().createLog(context, new Log { UserCreated = user .... });    
       }

      context.SaveChanges(); 
   } 
ssilas777
  • 9,672
  • 4
  • 45
  • 68
-1

Not solve because I can have the list of "users" duplication of CPF. Besides, that way, my class "UserDomain" would be having more of a liability, wounding patterns.

Junior
  • 199
  • 1
  • 9