Prevent Entity Framework to automatically attach entities - c#

I'm using the Entity Framework, and it's entities are used are Database representation AND business object.
So it means that some entities that are manipulated should always stay detached from the context.
I managed to read and write data from the database but I have a small problem when updating:
I have a table "Stock" which is linked to one table "Warehouse".
The current process is this one (simplified, but the spirit remains, there are more fields):
a new object Stock is created and its fields are filled with some values (date...)
the current Warehouse (object pulled for the entire request from the database) is associated to the Stock object
the object is sent to the DAL method which work is to save it.
The DAL method checks if the Stock item already exist for the day (same date, depot and same type) in the database
If it exist, the method updates the volume from the pulled object and save the changes.
Else, the new Stock object is inserted.
The problem here is that when I create the new Stock object and associate it to the Warehouse, the object EntityState is automatically set to "Added". So when I perform a SaveChanges() and the Stock already exist, the line is updated AND a new Stock line is added...
What I would want is to keep the new Stock object Detached until I attach it myself. I don't want that it happens automatically.
The only solution I found is to Detach the new object from the context before saving if the object already exist.
I could also Detach() the Warehouse object but that's not a satisfying solution I think as in the real case there are more items to associate and I'm not sure that's a good idea to play with Attach() and Detach() on them.
In this case, until I "Add" it to the context myself, the object is only a "Transport" object and I'd like it to stay out of the context.
Any idea on how I could keep the Stock object detached ?
Code (it may be a little incorrect, I wrote it by memory) :
Stock stk = new Stock();
stk.Date = DateTime.Now;
stk.Volume = 100; //so far stk is "Detached" and that's cool.
stk.Warehouse = CurrentWarehouse; //stk become "Added" and that's less cool.
DAL.Stock.Instance.Save(stk);
In Save():
var existing = (from s in Context.CurrentContext.Stock
where s.Warehouse.WarehouseId == stk.Warehouse.WarehouseId && s.Date == stk.Date && s.Type == 2
select s).FirstOfDefault();
if(existing != null)
{
existing.Volume = stk.Volume;
Context.CurrentContext.Detach(stk); //I find it a stupid workaround !!!!!!
}
else
{
Context.CurrentContext.AddToStock(stk); //what I would want to do.
}
Context.CurrentContext.SaveChanges()

You probably just want to set the MergeOption to an appropriate value. NoTracking would keep everything in a detached state, and allow you to perform your manual work. There are probably other ways to do this, but I'm doing something similar by setting MergeOption to detached.
http://msdn.microsoft.com/en-us/library/system.data.services.client.dataservicecontext.mergeoption.aspx

Related

EntityFramework Core - Copying an entity and placing it back into the database

Is there a best practice for doing a copy of an entity, making some changes to it based on user input, and then re-inserting it into the database?
Some other Stackoverflow threads have mentioned that EF will handle inserting new objects for you even if the same primary key exists in the database, but I'm not quite sure that's how EF Core is handling it. Whenever I try and copy an object I get an error of
Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF
Basically I just need a clean way to copy an object, make some changes to it based on user input, and then insert that copy back into the database, and have the Id auto-increment properly. Is there a best practice or simple way of doing this without having to manually set properties to null or empty?
EDIT: Example code for retrieving the object from the database:
public Incident GetIncidentByIdForCloning(int id)
{
try
{
return _context.Incident.Single(i => i.IncidentId == id);
}
catch
{
return null;
}
}
Code after retrieving object (As some fields are auto-generated like RowVersion which is a Timestamp):
public IActionResult Clone([FromBody]Incident Incident)
{
var incidentToCopy = _incidentService.IncidentRepository.GetIncidentByIdForCloning(Incident.IncidentId);
incidentToCopy.IncidentTrackingRefId = _incidentService.IncidentRepository.GetNextIdForIncidentCategoryAndType(
Incident.IncidentCategoryLookupTableId, Incident.IncidentTypeLookupTableId).GetValueOrDefault(0);
incidentToCopy.RowVersion = null;
incidentToCopy.IncidentId = 0; //This will fail with or without this line, this was more of a test to see if manually setting would default the insert operation, such as creating a brand new object would normally do.
incidentToCopy.IncidentCategoryLookupTableId = Incident.IncidentCategoryLookupTableId;
incidentToCopy.IncidentTypeLookupTableId = Incident.IncidentTypeLookupTableId;
var newIncident = _incidentService.IncidentRepository.CreateIncident(incidentToCopy);
...
I realize I could just make an entirely new object and do left-hand copying, but that seems terribly inefficient and I want to know if EF Core offers better solutions.
So I went through the "Possible duplicate" thread a bit more than I did when I initially stumbled upon it before creating this one, and there was a not-so-highly upvoted solution that I overlooked that essentially just grabs all of the values at once when retrieving the object from the database - and it doesn't retrieve a reference to that object in the process. My code now looks something like this:
try
{
var incidentToCopy = _context.Incident.Single(i => i.IncidentId == id);
return (Incident) _context.Entry(incidentToCopy).CurrentValues.ToObject();
}
In your IncidentRepository class try getting the Incident by using AsNoTracking and it should get tracked as a new entity when it is added.
public void Clone(int id)
{
// Prevent tracking changes to the object.
var incident = _context.AsNoTracking().SingleOrDefault(i => i.Id == id);
// Setting back to 0 should treat the object Id as unset.
incident.Id = 0;
// Add the Incident while it is untracked will treat it as a new entity.
_context.Incidents.Add(incident);
_context.SaveChanges();
}
I believe what is happening here is the following:
When you retrieve a value from the database, it gets stored in something like
context.ChangeTracker.Entries<Incident>
Which is a collection of Incident entries being tracked. When you change the id property of the incident object you've retrieved you are sort of abusing the ChangeTracker in the name of efficiency. The ChangeTracker does not believe you have created a new object. You might be able to try something like finding the entry in the ChangeTracker and set it's state to detached then after you've set the id to 0 add the object back to the context.DbSet but at that point you have probably made things way more complicated than simply copying the object.

An object with the same key already exists in the ObjectStateManager

I have a scenario that could not find the solution for it and need some help
How can I achieve this,
I’d like to get current record for the client modify it and instead of update I’d like to add the new record to table for historical change information
client c = new client();
using (DBEntities db = new DBEntities())
{
// get current records in the client table for client
IQueryable<client> co = from p in db.client where p.CUS_NUMBER == scd.cus_number && p.isCurrent == true select p;
c = co.First();
//update email and and address
c.EMAIL = Helper.CleanInput("mymail#mm.com");
c.ADDRESS = Helper.CleanInput("123 Sheppard");
//instead of updating current record I'd like to add new record to the table to keep historical changes
db.AddToclient(c);
db.SaveChanges();
//I get error that
//An object with the same key already exists in the ObjectStateManager.
//The existing object is in the Modified state. An object can only be added to
//the ObjectStateManager again if it is in the added state.
Complete error
An object with the same key already exists in the ObjectStateManager. The existing object is in the Modified state. An object can only be added to the ObjectStateManager again if it is in the added state.
remove this code db.AddToclient(c); ,rest all is fine,You are already accessing the object by its reference so no need to add it again.It'll get modified when you call savechanges()
or use cloning if you want to add new object c = co.First().Clone();
It's look like you are adding same row to database and error is coming due to addition of same row again having same primary key which DB will not allow.
Try to add new row and make another table that keeps Historical information of old row and a reference as foreign key. You can add a boolean field that keep information regarding deletion let It is IsDeleted.
Hope It will Help
Thanks
The reason db.AddToclient(c); gives the error is because this object is being tracked by the object context, by possibly being in the database.
The best way to accomplish what you are trying to do is something like the following:
var newClient = new client()
{
EMAIL = Helper.CleanInput("mymail#mm.com"),
ADDRESS = Helper.CleanInput("123 Sheppard"),
};
db.AddToclient(newClient);
db.SaveChanges();
In Entity Framework, all objects retrieved from database by default are tracked by ObjectContext instance. Entity Framework internally maps all objects being tracked by his Key. This pattern is called Identity Map. This means that there will be only one instance of an entity per key. So, you don't need to call Add again, since the entity is already on EF map. You just need call SaveChanges to persist modified entities.
In your case you are:
1 - Creating a new instance of EF ObjectContext;
2 - Retrieving entities in your LINQ query;
3 - Changing values of properties of the retrieved entity;
4 - Adding again to the ObjContext; //error!
5 - Calling SaveChanges()
Step 4 is not necessary because the ObjectContext already knows about the retrieved objects.

Update an EntityObject with an another EntityObject

I have a little problem and I need your help with it. I'm using Entity Framework for database handling and I want to update a dataset in this database.
I have an EntityObject with all the changes and want to be able to update this Object with existing Object.
I'm using the following code to update the data:
IQueryable<Competitors> getCompetitor = DatabaseObject.Competitors.Where(SelectOnly => SelectOnly.competitorID == competitorObject.competitorID);
Competitors competitor = getCompetitor.First();
competitor = competitorObject;
DatabaseObject.SaveChanges();
But this deosn't work. How can I update the date in database?
Assuming, that your competitorObject is of Competitors type (competitor = competitorObject), you have to attach it to your context, mark it as modified, and then save changes:
DatabaseObject.Competitors.Attach(competitorObject);
DatabaseObject.Entry(competitorObject).State = EntityState.Modified;
DatabaseObject.SaveChanges();
There's no need to retrieve source object in your case, but without attaching, the context knows nothing about your updated object.
The piece of code, which is marking an object as modified, can be a little different, if you're using ObjectContext API instead of DbContext API:
DatabaseObject.ObjectStateManager.GetObjectStateEntry(competitorObject).SetModified();
The only change you need to make to your code to get it to work is update at least one property on the fetched entity. You are updating the reference, not the property values so like this:
IQueryable<Competitors> getCompetitor = DatabaseObject.Competitors.Where(SelectOnly => SelectOnly.competitorID == competitorObject.competitorID);
Competitors competitor = getCompetitor.First();
competitor.Name = competitorObject.Name;
competitor.Contact = competitorObject.Contact;
DatabaseObject.SaveChanges();
Or as Dennis has said you can attach the CompetitorObject to the context and mark it as modified. Doing it that way will override all the properties of the existing Competitors record with the values of CompetitorObject.

Entity Framework 4 merge data to tracked entity

I'm struggling with Entity Framework code first and merging.
I have an MVC controller with a generic repository. A view model gets posted up and I convert that into the type that EF knows about
var converted = AutoMapper.Mapper.Map<RoutineViewModel, Routine>(result);
_routineRepository.Update(converted);
In the repository I have:
/*
Routines.Attach(item);
ChangeTracker.Entries<Routine>().Single(x => x.Entity.Id == item.Id).State = EntityState.Modified;*/
var match = Routines.Single(x => x.Id == item.Id);
var entity = Entry(match);
entity.CurrentValues.SetValues(item);
I commented out the first bit because it was throwing an error about already tracking the entity even though a check like this:
if (ChangeTracker.Entries<Routine>().Count(x => x.Entity.Id == item.Id) != 0)
returned false
The problem I'm having is that the Routine object has an ICollection property of Steps. When I set the values of the tracked entity to match that of the poco the ICollection changes aren't propagated down. Looking around this site there looks to be a few nasty looking recursive calls. Is this really how it works or am I missing something?
Is there any easy way to say, here is the source object (untracked), copy everything about it into the tracked object?
Just to be clear I don't think that getting the object first and updating the properties on that should be done outside of the repository. That seems to not only force you to pass your data models across domain boundaries but seems like instead of an equivalent SQL like statement being (update x,y where id = 1), to (insert into temp table where id = 1, for reach row in temp table, update x..... now for each row in table update table x = tempx where id = 1)
Edit --
So the problem is with the setValues not being a recursive call. The routine object has 2 simple properties (id and name) and one complex (ICollection ). If the item coming in has the name changed and some steps changed, setValues picks up the name change but doesn't apply to the children. Is there some other way to do this? It seems a little creaky to me that I have to hand roll this functionality
From what i can tell you are creating your entity, populating properties and then attaching it to the DB. This is kinda the wrong way round with EF.
If you want to attach an object which is already in the DB but isnt being tracked, you can use attach but only changes made after the attach call are recorded to be committed to the DB. If you want to use attach make sure you make your changes after calling that method.
In addition EF only allows you to attach an object which is not currently in the object graph. So if you try to attach the same object twice (or one with the same key) you will be given an error such as the one you are seeing.

How do you save a Linq object if you don't have its data context?

I have a Linq object, and I want to make changes to it and save it, like so:
public void DoSomething(MyClass obj) {
obj.MyProperty = "Changed!";
MyDataContext dc = new MyDataContext();
dc.GetTable<MyClass>().Attach(dc, true); // throws exception
dc.SubmitChanges();
}
The exception is:
System.InvalidOperationException: An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.
It looks like I have a few choices:
put a version member on every one of my Linq classes & tables (100+) that I need to use in this way.
find the data context that originally created the object and use that to submit changes.
implement OnLoaded in every class and save a copy of this object that I can pass to Attach() as the baseline object.
To hell with concurrency checking; load the DB version just before attaching and use that as the baseline object (NOT!!!)
Option (2) seems the most elegant method, particularly if I can find a way of storing a reference to the data context when the object is created. But - how?
Any other ideas?
EDIT
I tried to follow Jason Punyon's advice and create a concurrency field on on table as a test case. I set all the right properties (Time Stamp = true etc.) on the field in the dbml file, and I now have a concurrency field... and a different error:
System.NotSupportedException: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.
So what the heck am I supposed to attach, then, if not an existing entity? If I wanted a new record, I would do an InsertOnSubmit()! So how are you supposed to use Attach()?
Edit - FULL DISCLOSURE
OK, I can see it's time for full disclosure of why all the standard patterns aren't working for me.
I have been trying to be clever and make my interfaces much cleaner by hiding the DataContext from the "consumer" developers. This I have done by creating a base class
public class LinqedTable<T> where T : LinqedTable<T> {
...
}
... and every single one of my tables has the "other half" of its generated version declared like so:
public partial class MyClass : LinqedTable<MyClass> {
}
Now LinqedTable has a bunch of utility methods, most particularly things like:
public static T Get(long ID) {
// code to load the record with the given ID
// so you can write things like:
// MyClass obj = MyClass.Get(myID);
// instead of:
// MyClass obj = myDataContext.GetTable<MyClass>().Where(o => o.ID == myID).SingleOrDefault();
}
public static Table<T> GetTable() {
// so you can write queries like:
// var q = MyClass.GetTable();
// instead of:
// var q = myDataContext.GetTable<MyClass>();
}
Of course, as you can imagine, this means that LinqedTable must somehow be able to have access to a DataContext. Up until recently I was achieving this by caching the DataContext in a static context. Yes, "up until recently", because that "recently" is when I discovered that you're not really supposed to hang on to a DataContext for longer than a unit of work, otherwise all sorts of gremlins start coming out of the woodwork. Lesson learned.
So now I know that I can't hang on to that data context for too long... which is why I started experimenting with creating a DataContext on demand, cached only on the current LinqedTable instance. This then led to the problem where the newly created DataContext wants nothing to do with my object, because it "knows" that it's being unfaithful to the DataContext that created it.
Is there any way of pushing the DataContext info onto the LinqedTable at the time of creation or loading?
This really is a poser. I definitely do not want to compromise on all these convenience functions I've put into the LinqedTable base class, and I need to be able to let go of the DataContext when necessary and hang on to it while it's still needed.
Any other ideas?
Updating with LINQ to SQL is, um, interesting.
If the data context is gone (which in most situations, it should be), then you will need to get a new data context, and run a query to retrieve the object you want to update. It's an absolute rule in LINQ to SQL that you must retrieve an object to delete it, and it's just about as iron-clad that you should retrieve an object to update it as well. There are workarounds, but they are ugly and generally have lots more ways to get you in trouble. So just go get the record again and be done with it.
Once you have the re-fetched object, then update it with the content of your existing object that has the changes. Then do a SubmitChanges() on the new data context. That's it! LINQ to SQL will generate a fairly heavy-handed version of optimistic concurrency by comparing every value in the record to the original (in the re-fetched) record. If any value changed while you had the data, LINQ to SQL will throw a concurrency exception. (So you don't need to go altering all your tables for versioning or timestamps.)
If you have any questions about the generated update statements, you'll have to break out SQL Profiler and watch the updates go to the database. Which is actually a good idea, until you get confidence in the generated SQL.
One last note on transactions - the data context will generate a transaction for each SubmitChanges() call, if there is no ambient transaction. If you have several items to update and want to run them as one transaction, make sure you use the same data context for all of them, and wait to call SubmitChanges() until you've updated all the object contents.
If that approach to transactions isn't feasible, then look up the TransactionScope object. It will be your friend.
I think 2 is not the best option. It's sounding like you're going to create a single DataContext and keep it alive for the entire lifetime of your program which is a bad idea. DataContexts are lightweight objects meant to be spun up when you need them. Trying to keep the references around is also probably going to tightly couple areas of your program you'd rather keep separate.
Running a hundred ALTER TABLE statements one time, regenerating the context and keeping the architecture simple and decoupled is the elegant answer...
find the data context that originally created the object and use that to submit changes
Where did your datacontext go? Why is it so hard to find? You're only using one at any given time right?
So what the heck am I supposed to attach, then, if not an existing entity? If I wanted a new record, I would do an InsertOnSubmit()! So how are you supposed to use Attach()?
You're supposed to attach an instance that represents an existing record... but was not loaded by another datacontext - can't have two contexts tracking record state on the same instance. If you produce a new instance (ie. clone) you'll be good to go.
You might want to check out this article and its concurrency patterns for update and delete section.
The "An entity can only be attached as modified without original state if it declares a version member" error when attaching an entitity that has a timestamp member will (should) only occur if the entity has not travelled 'over the wire' (read: been serialized and deserialized again). If you're testing with a local test app that is not using WCF or something else that will result in the entities being serialized and deserialized then they will still keep references to the original datacontext through entitysets/entityrefs (associations/nav. properties).
If this is the case, you can work around it by serializing and deserializing it locally before calling the datacontext's .Attach method. E.g.:
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);
}
}
Alternatively you can detach it by setting all entitysets/entityrefs to null, but that is more error prone so although a bit more expensive I just use the DataContractSerializer method above whenever I want to simulate n-tier behavior locally...
(related thread: http://social.msdn.microsoft.com/Forums/en-US/linqtosql/thread/eeeee9ae-fafb-4627-aa2e-e30570f637ba )
You can reattach to a new DataContext. The only thing that prevents you from doing so under normal circumstances is the property changed event registrations that occur within the EntitySet<T> and EntityRef<T> classes. To allow the entity to be transferred between contexts, you first have to detach the entity from the DataContext, by removing these event registrations, and then later on reattach to the new context by using the DataContext.Attach() method.
Here's a good example.
When you retrieve the data in the first place, turn off object tracking on the context that does the retrieval. This will prevent the object state from being tracked on the original context. Then, when it's time to save the values, attach to the new context, refresh to set the original values on the object from the database, and then submit changes. The following worked for me when I tested it.
MyClass obj = null;
using (DataContext context = new DataContext())
{
context.ObjectTrackingEnabled = false;
obj = (from p in context.MyClasses
where p.ID == someId
select p).FirstOrDefault();
}
obj.Name += "test";
using (DataContext context2 = new ())
{
context2.MyClasses.Attach(obj);
context2.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, obj);
context2.SubmitChanges();
}

Categories

Resources