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