Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Alright, so the problem I'm having is trying to update a virtual list of objects within a model to Microsoft Sql Server.

My Class looks like this

C#
public class CustomObject
{
    public int Id { get; set; }
    public string origin { get; set; }
    public Type Type { get; set; }
    public virtual List<CustomObject> CustomObjects { get; set; }
}

and when I try something like

C#
dbContext.CustomObjects.Add(customObjects);

it works fine, but when I try something like

C#
var customObject = dbContext.CustomObjects.Find(Id);
customObject = newObject;
dbContext.Entry(customObject).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();

it seems to update the information like the origin but not the CustomObjects variable in Microsoft Sql.
Posted

1 solution

First, I assume CustomObjects is declared as a DbSet<customobject></customobject> in your DbContext class.

Here you are pulling a record from the SQL table:
C#
var customObject = dbContext.CustomObjects.Find(Id);


Here it appears you then replacing the object you just pulled from the DB with one you (I'm assuming) created within your application:
C#
customObject = newObject;


Finally you attempt to set the object's state to modified and save it, which doesn't work:
C#
dbContext.Entry(customObject).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();


I think your problem lies in the customObject = newObject; line because you are completely replacing the object you just pulled with a new object, including the primary key.

Try updating individual properties of the object instead of overwriting the object in it's entirety.

I think your example code is closer to the following:
C#
var customObject = dbContext.CustomObjects.Find(Id);
dbContext.CustomObjects.Remove(customObject);
dbContext.SaveChanges();
dbContext.CustomObjects.Add(newObject);
dbContext.SaveChanges();
 
Share this answer
 
Comments
Member 11806612 2-Jul-15 9:29am    
Alright so I tried changing it to
customObject.CustomObjects = newObject.CustomObjects;
dbContext.Entry(customObject).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();

and its not updating properly.
Mark Miller 2-Jul-15 10:26am    
Try this:

// Find existing record, load into object
var customObject = dbContext.CustomObjects.Find(Id);

// Set individual properties on the object pulled from the DB
customObject.Property1 = newObject.Property1;
customObject.Property2 = newObject.Property2;
dbContext.Entry(customObject).State = System.Data.EntityState.Modified;
dbContext.SaveChanges();

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900