Entity framework 4 Enity Framework 4.1-单程数据库更新

Entity framework 4 Enity Framework 4.1-单程数据库更新,entity-framework-4,entity-framework-4.1,Entity Framework 4,Entity Framework 4.1,假设我有以下代码: class Score { public Update(int score) { update score but do not call (context.SaveChanges()) } } class Foo { public DoSomething(int update) { Score score = new Score(); score.Updat

假设我有以下代码:

class Score
{
     public Update(int score)
     {
         update score but do not call (context.SaveChanges())
     }
}

 class Foo
 {
     public DoSomething(int update)
     {
           Score score = new Score();
           score.Update(2);
           SomeObj obj = (select object);
           obj.Soo = 3;
           context.SaveChanges();
      }
 }
基本上为了让它工作,我需要在方法更新中明确地提供SaveChanges。但当我有4个这样的方法在行中,并且34243个用户想要更新数据时,我不认为在4次旅行中保存每一个方法是一个好主意

在提供的示例中,EF4.1中有没有办法将数据库更新延迟到最后一刻,或者我被迫为每个方法明确保存

编辑: 请澄清。我试着不在外部方法中调用SaveChanges,而只在其中一次保存更改

我将举一个真实的例子:

public class ScoreService : IScoreService
{
private JamiContext _ctx;
    private IRepository<User> _usrRepo;
    public ScoreService(IRepository<User> usrRepo)
    {
        _ctx = new JamiContext();
        _usrRepo = usrRepo;
    }

    public void PostScore(int userId, GlobalSettings gs, string name)
    {
        User user = _ctx.UserSet.Where(x => x.Id == userId).FirstOrDefault();
        if (name == "up")
        {
            user.Rating = user.Rating + gs.ScoreForLike;
        }
        else if (name == "down")
        {
            user.Rating = user.Rating - Math.Abs(gs.ScoreForDislike);
        }
    }
 }

在这种情况下,除非我在PostScore中调用SaveChanges,否则用户评级不会更新。将数据库更新延迟到最后一刻的方法是在最后一刻才调用SaveChanges


您可以完全控制此代码,如果您的代码在每次更新后都调用SaveChanges,则需要进行更改。

在您的示例中,类似于
PostScore
LikeDislike
使用不同的上下文实例。这就是问题的根源,在这种情况下,无法避免调用多个
SaveChanges
。整个操作是单个工作单元,因此应该使用单个上下文实例。在这种情况下使用多个上下文实例是错误的设计


无论如何,即使您调用single
SaveChanges
,对于每个更新、插入或删除的实体,您仍将有单独的数据库往返,因为EF不支持命令批处理。

这并不能真正解决我的整个问题,但至少我可以使用上下文的单个实例: 对于Ninject:

Bind<JamiContext>().To<JamiContext>().InRequestScope();
Bind().To().InRequestScope();
然后是构造器:

private JamiContext _ctx;
    private IRepository<User> _usrRepo;
    public ScoreService(IRepository<User> usrRepo, JamiContext ctx)
    {
        _ctx = ctx;
        _usrRepo = usrRepo;
    }
private JamiContext\u ctx;
私人IRepository_usrRepo;
公共计分服务(IRepository usrRepo、JamiContext ctx)
{
_ctx=ctx;
_usrRepo=usrRepo;
}

如果要延迟更新,为什么要在更新方法中调用
SaveChanges
?你的例子很不清楚。我不知道为什么我写了“不调用(context.SaveChanges()”,看看“不调用”(;这很可能只是暂时的、不好的解决方案,因为上下文永远不应该是单例、静态、共享或其他任何形式。上下文应该用于单个逻辑操作:(上下文也不是线程安全的).那么我宁愿使用.InRequestScope()?
private JamiContext _ctx;
    private IRepository<User> _usrRepo;
    public ScoreService(IRepository<User> usrRepo, JamiContext ctx)
    {
        _ctx = ctx;
        _usrRepo = usrRepo;
    }