为什么我的 DataContext 看不到对象(工作单元)的更改?

发布于 2024-10-13 23:41:49 字数 5200 浏览 4 评论 0原文

我正在尝试建立一个使用 UnitOfWork 和存储库模式的项目。

现在我无法使用 IoC 和 EF4,所以我尝试使用 Linq 和 DataContext,但有一点依赖性:(。我毫不掩饰我对所有这些概念的集成有点困惑。我注意到调试我的代码,DataContext 没有看到对对象进行的更新,但每次它向数据库添加新实体时,

我都读了很多内容,但我找不到我的问题,也许这是一个简单的步骤。在继续之前,这是我所拥有的:

例如,我有一个名为 foo 的对象...我有 foo 控制器,它在构造函数中创建了 fooRepository 的新实例。 DataContext...是吗? 这是我的代码

public class ListaController : Controller
{

    IListaRepository _listaRepository;       

    public ListaController()
        : this(new ListaRepository()) {
    }

    public ListaController(IListaRepository repository)
    {
        _listaRepository = repository;
    }

    [HttpPost]
    public ActionResult Edit(int id, Lista lista)
    {
        try
        {
            this._listaRepository.Save(lista);
            return RedirectToAction("Index");

        }
        catch
        {
            return View();
        }
    }
}

   public class ListaRepository : LinqRepository<Lista>, IListaRepository 
   {

    protected IUnitOfWork uow
    {
        get { return base.GetCurrentUnitOfWork<IUnitOfWork>(); }
    }

    public ListaRepository()
        : base()
    {
    }

    public override void Add(Lista lista)
    {
        this.uow.Context.Listas.InsertOnSubmit(lista);
        this.uow.Commit();
    }

    public override void Save(Lista lista)
    {
        Add(lista);
    }
   }

   public static class UnitOfWork
   {
    private const string HTTPCONTEXTKEY = "Domain.HttpContext.Key";

    private static IUnitOfWorkFactory _unitOfWorkFactory;
    private static readonly Hashtable _threads = new Hashtable();

    public static void Commit()
    {
        IUnitOfWork unitOfWork = GetUnitOfWork();
        if (unitOfWork != null)
        {
            unitOfWork.Commit();
        }
    }

    public static IUnitOfWork Current
    {
        get
        {
            IUnitOfWork unitOfWork = GetUnitOfWork();
            if (unitOfWork == null)
            {
                //Qui inserisco dipendenza in quanto non uso un IoC
                //_unitOfWorkFactory = ObjectFactory.GetInstance<IUnitOfWorkFactory>();
                _unitOfWorkFactory = new LinqUnitOfWorkFactory();
                unitOfWork = _unitOfWorkFactory.Create();
                SaveUnitOfWork(unitOfWork);
            }
            return unitOfWork;
        }
    }

    private static IUnitOfWork GetUnitOfWork()
    {
        if (HttpContext.Current != null)
        {
            if (HttpContext.Current.Items.Contains(HTTPCONTEXTKEY))
            {
                return (IUnitOfWork)HttpContext.Current.Items[HTTPCONTEXTKEY];
            }
            return null;
        }
        else
        {
            Thread thread = Thread.CurrentThread;
            if (string.IsNullOrEmpty(thread.Name))
            {
                thread.Name = Guid.NewGuid().ToString();
                return null;
            }
            else
            {
                lock (_threads.SyncRoot)
                {
                    return (IUnitOfWork)_threads[Thread.CurrentThread.Name];
                }
            }
        }
    }

    private static void SaveUnitOfWork(IUnitOfWork unitOfWork)
    {
        if (HttpContext.Current != null)
        {
            HttpContext.Current.Items[HTTPCONTEXTKEY] = unitOfWork;
        }
        else
        {
            lock (_threads.SyncRoot)
            {
                _threads[Thread.CurrentThread.Name] = unitOfWork;
            }
        }
    }
  }

public abstract class LinqRepository<T> : IRepository<T> where T : class
{
    protected ManagerEmailDataContext _context = new ManagerEmailDataContext();

    protected ManagerEmailDataContext Context
    {
        get
        {
            if (_context == null)
            {
                _context = GetCurrentUnitOfWork<LinqUnitOfWork>().Context;
            }
            return _context;
        }
    }

    public TUnitOfWork GetCurrentUnitOfWork<TUnitOfWork>() where TUnitOfWork : IUnitOfWork
    {
        return (TUnitOfWork)UnitOfWork.Current;
    }


    public abstract IQueryable<T> GetAll();
    public abstract void Add(T entity);
    public abstract void Save(T entity);
    public abstract T Get(int id);
}

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    LinqUnitOfWorkFactory.SetDataContext(() => new ManagerEmailDataContext());
}

public class LinqUnitOfWorkFactory : ManagerEmail.Models.IUnitOfWorkFactory
{
    private static Func<ManagerEmailDataContext> _objectContextDelegate;
    private static readonly Object _lockObject = new object();

    public static void SetDataContext(Func<ManagerEmailDataContext> objectDataContextDelegate)
    {
        _objectContextDelegate = objectDataContextDelegate;
    }

    public IUnitOfWork Create()
    {
        ManagerEmailDataContext context;
        lock (_lockObject)
        {
            context = _objectContextDelegate();
        }
        return new LinqUnitOfWork(context);
    }
}`enter code here`

任何帮助或建议将不胜感激!

抱歉,如果我发布了所有代码,但是大约一周后我对这件事感到疯狂。

I'm trying to set up a project that use UnitOfWork and Repository pattern.

Now I can't use an IoC and EF4, so I'm trying with Linq and the DataContext with a bit of dependency :(. I don't hide that I'm a bit confused about the integration of all these concepts. I noticed debugging my code that the DataContext doesn't see the updates made to an object, but every time it adds a new entity to database.

I have read a lot about, but I can't find my problem, maybe it's a simple step. Before I proceed, here's what I have:

For example I have an object called foo...I have the foo controller that in the constructor creates a new instance of fooRepository. In the fooRepository I add a reference to my UnitOfWork that wraps the DataContext...Is that right?
Here's my code

public class ListaController : Controller
{

    IListaRepository _listaRepository;       

    public ListaController()
        : this(new ListaRepository()) {
    }

    public ListaController(IListaRepository repository)
    {
        _listaRepository = repository;
    }

    [HttpPost]
    public ActionResult Edit(int id, Lista lista)
    {
        try
        {
            this._listaRepository.Save(lista);
            return RedirectToAction("Index");

        }
        catch
        {
            return View();
        }
    }
}

   public class ListaRepository : LinqRepository<Lista>, IListaRepository 
   {

    protected IUnitOfWork uow
    {
        get { return base.GetCurrentUnitOfWork<IUnitOfWork>(); }
    }

    public ListaRepository()
        : base()
    {
    }

    public override void Add(Lista lista)
    {
        this.uow.Context.Listas.InsertOnSubmit(lista);
        this.uow.Commit();
    }

    public override void Save(Lista lista)
    {
        Add(lista);
    }
   }

   public static class UnitOfWork
   {
    private const string HTTPCONTEXTKEY = "Domain.HttpContext.Key";

    private static IUnitOfWorkFactory _unitOfWorkFactory;
    private static readonly Hashtable _threads = new Hashtable();

    public static void Commit()
    {
        IUnitOfWork unitOfWork = GetUnitOfWork();
        if (unitOfWork != null)
        {
            unitOfWork.Commit();
        }
    }

    public static IUnitOfWork Current
    {
        get
        {
            IUnitOfWork unitOfWork = GetUnitOfWork();
            if (unitOfWork == null)
            {
                //Qui inserisco dipendenza in quanto non uso un IoC
                //_unitOfWorkFactory = ObjectFactory.GetInstance<IUnitOfWorkFactory>();
                _unitOfWorkFactory = new LinqUnitOfWorkFactory();
                unitOfWork = _unitOfWorkFactory.Create();
                SaveUnitOfWork(unitOfWork);
            }
            return unitOfWork;
        }
    }

    private static IUnitOfWork GetUnitOfWork()
    {
        if (HttpContext.Current != null)
        {
            if (HttpContext.Current.Items.Contains(HTTPCONTEXTKEY))
            {
                return (IUnitOfWork)HttpContext.Current.Items[HTTPCONTEXTKEY];
            }
            return null;
        }
        else
        {
            Thread thread = Thread.CurrentThread;
            if (string.IsNullOrEmpty(thread.Name))
            {
                thread.Name = Guid.NewGuid().ToString();
                return null;
            }
            else
            {
                lock (_threads.SyncRoot)
                {
                    return (IUnitOfWork)_threads[Thread.CurrentThread.Name];
                }
            }
        }
    }

    private static void SaveUnitOfWork(IUnitOfWork unitOfWork)
    {
        if (HttpContext.Current != null)
        {
            HttpContext.Current.Items[HTTPCONTEXTKEY] = unitOfWork;
        }
        else
        {
            lock (_threads.SyncRoot)
            {
                _threads[Thread.CurrentThread.Name] = unitOfWork;
            }
        }
    }
  }

public abstract class LinqRepository<T> : IRepository<T> where T : class
{
    protected ManagerEmailDataContext _context = new ManagerEmailDataContext();

    protected ManagerEmailDataContext Context
    {
        get
        {
            if (_context == null)
            {
                _context = GetCurrentUnitOfWork<LinqUnitOfWork>().Context;
            }
            return _context;
        }
    }

    public TUnitOfWork GetCurrentUnitOfWork<TUnitOfWork>() where TUnitOfWork : IUnitOfWork
    {
        return (TUnitOfWork)UnitOfWork.Current;
    }


    public abstract IQueryable<T> GetAll();
    public abstract void Add(T entity);
    public abstract void Save(T entity);
    public abstract T Get(int id);
}

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
    LinqUnitOfWorkFactory.SetDataContext(() => new ManagerEmailDataContext());
}

public class LinqUnitOfWorkFactory : ManagerEmail.Models.IUnitOfWorkFactory
{
    private static Func<ManagerEmailDataContext> _objectContextDelegate;
    private static readonly Object _lockObject = new object();

    public static void SetDataContext(Func<ManagerEmailDataContext> objectDataContextDelegate)
    {
        _objectContextDelegate = objectDataContextDelegate;
    }

    public IUnitOfWork Create()
    {
        ManagerEmailDataContext context;
        lock (_lockObject)
        {
            context = _objectContextDelegate();
        }
        return new LinqUnitOfWork(context);
    }
}`enter code here`

Any help or suggest will be appreciated!

Sorry if I posted all the code, but It's about a week that I'm going crazy with this thing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我们只是彼此的过ke 2024-10-20 23:41:49

该问题与 LINQ 有关。在我的控制器中,我调用 Save(T实体) 方法,在我的存储库中,我

public override void Save(Lista lista)
{
   Lista original = CloneEntity<Lista>(this.Get(lista.Id));
   this._uow = new LinqUnitOfWorkFactory().Create(); //I must renew the DataContext
   this._uow.Context.Listas.Attach(lista, original);
   this._uow.Context.Refresh(RefreshMode.KeepChanges, lista);
   this._uow.Commit();
}

internal static T CloneEntity<T>(T originalEntity)
{
   Type entityType = typeof(T);
   DataContractSerializer ser = new DataContractSerializer(entityType);
   using (MemoryStream ms = new MemoryStream())
   {
       ser.WriteObject(ms, originalEntity);
       ms.Position = 0;
       return (T)ser.ReadObject(ms);
   }
}

希望这对某人有帮助。

The problem is related with LINQ. In my controller I call the Save(T entity) method and in my repository I have

public override void Save(Lista lista)
{
   Lista original = CloneEntity<Lista>(this.Get(lista.Id));
   this._uow = new LinqUnitOfWorkFactory().Create(); //I must renew the DataContext
   this._uow.Context.Listas.Attach(lista, original);
   this._uow.Context.Refresh(RefreshMode.KeepChanges, lista);
   this._uow.Commit();
}

internal static T CloneEntity<T>(T originalEntity)
{
   Type entityType = typeof(T);
   DataContractSerializer ser = new DataContractSerializer(entityType);
   using (MemoryStream ms = new MemoryStream())
   {
       ser.WriteObject(ms, originalEntity);
       ms.Position = 0;
       return (T)ser.ReadObject(ms);
   }
}

Hope this helps someone.

野味少女 2024-10-20 23:41:49

我看不到您在哪里调用 DataContext.SubmitChanges()。您的工作单元 Commit() 方法需要在某个时刻调用该方法以将更改保存到数据库。

I can't see where you're calling DataContext.SubmitChanges(). Your unit of work Commit() method needs to call that at some point to save the changes to the db.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文