Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top