This thread looks to be a little on the old side and therefore may no longer be relevant. Please see if there is a newer thread on the subject and ensure you're using the most recent build of any software if your question regards a particular product.
This thread has been locked and is no longer accepting new posts, if you have a question regarding this topic please email us at support@mindscape.co.nz
|
Hello. What's the best way to determine if an entity is detached? For some context... I have a method that may or may not be called within the scope of a UOW and don't want to create a UOW needlessly. |
|
|
Does Entity.UnitOfWork == null do it? |
|
|
As chadw correctly pointed out, testing UnitOfWork == null is the correct way to determine this. This can only be checked by the entity itself so you will want to set up a property on your entity e.g.
|
|
|
Thanks, chadw. And thanks, jeremy, for the detail regarding needing to add the prop to the entity. Anyone see a problem with this approach (using the 0. Getting Started sample project for commonality purposes): public sealed class UnitOfWork : IDisposable { public LightSpeedContext To use it, instead of doing: using (var uow = _context.CreateUnitOfWork()) { //stuff } One would use: using (var uow = new UnitOfWork(_context).CreateUnitOfWork()) { var movie = new Movie(); movie.Title = "Antitrust"; movie.Description = "A recent Standford graduate begins investigating the company and finds himself in the middle of several cybercrime scandals."; uow.Add(movie); uow.SaveChanges(); } If there was an existing entity, attached or not, one would use: using (var uow = new UnitOfWork(_context, existingMovie).CreateUnitOfWork()) { existingMovie.Title = "Antitrust (2001)"; uow.SaveChanges(); } If the entity has a unit of work it uses it, if not, a new instance is created. |
|
|
Two questions for you to help with my understanding on your intent here on your UnitOfWork class What would be the situation where you would find the Entity isn't detached assuming you are using this as a consistent scoping pattern for your UnitOfWork? The reason I ask is you are scoping via a using block so the UnitOfWork will get disposed meaning your entities would no longer be safe to carry around (they will throw an exception trying to access a disposed UnitOfWork). My other question would be what would be the main advantage for you over say:
Clearly since its a new UnitOfWork, the entity does need to be attached anyway to function in that scope.
|
|