为什么我的DataContext没有看到对象的变化(工作单位)?

时间:2011-01-25 11:07:36

标签: linq asp.net-mvc-3 repository-pattern unit-of-work

我正在尝试设置一个使用UnitOfWork和Repository模式的项目。

现在我不能使用IoC和EF4,所以我正在尝试使用Linq和DataContext但有点依赖:(。我不掩饰我对所有这些的集成感到有点困惑我注意到调试我的代码,DataContext没有看到对象所做的更新,而是每次向数据库添加一个新实体时。

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

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

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`

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

很抱歉,如果我发布了所有代码,但是大约一个星期我会对这件事感到疯狂。

2 个答案:

答案 0 :(得分:0)

问题与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);
   }
}

希望这有助于某人。

答案 1 :(得分:0)

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