【问题标题】:Two times calling the method "context.saveChanges"两次调用方法“context.saveChanges”
【发布时间】:2014-01-23 04:01:38
【问题描述】:

按照我的代码(只是演示疑问),这段代码我的服务中有一个接收用户列表并保存的方法,唯一的业务规则是检查用户是否已经存在。

还有那个电话的日志,这个想法很简单,它会安静地工作,我怀疑,我正在做 2 SaveChanges () 并且似乎是错误的,我该如何改进这段代码?我以为我只会在CreateUser 方法()中调用一次,但这很危险,因为“用户”列表中可能存在重复的 CPF,我必须创建一个验证此列表,但想避免这种情况,在我看来问题最少,我认为我在解决方案架构上犯了错误。

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

【问题讨论】:

标签: c# entity-framework


【解决方案1】:
   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(); 
   } 

【讨论】:

    【解决方案2】:

    无法解决,因为我可以拥有 CPF 的“用户”重复列表。此外,这样一来,我的“UserDomain”类就会有更多的责任和伤害模式。

    【讨论】:

    • 修改您的问题,而不是发表评论作为答案
    • 什么?我不明白
    猜你喜欢
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 2011-02-09
    • 2013-12-31
    • 2016-09-29
    相关资源
    最近更新 更多