I have a Model, We can call Person
// My table tb_person
public class Person
{
public int Id {get;set;}
public string Name {get; set;}
public int Age {get; set;}
public DateTime AddTime {get; set;}
public DateTime UPdateTime {get;set;}
public string Remark {get; set}
public bool IsEnable {get;set;}
}
First I get the Mdoel
using (var ctx = new MyEntitys())
{
ctx.Configuration.ProxyCreationEnabled = false;
ctx.Configuration.LazyLoadingEnabled = false;
Person firstModel = ctx.Persons.Where( x=> x.Id = 5).FirstOrDefault();
}
Now long time after I need to modify the Model, But I need to get the old model in Database and compare something.
using (var ctx = new MyEntitys())
{
ctx.Configuration.ProxyCreationEnabled = false;
ctx.Configuration.LazyLoadingEnabled = false;
Person CurrentModel = ctx.Persons.Where( x=> x.Id = 5).FirstOrDefault();
// Just a example for judge or compare
if (CurrentModel.IsEnable)
{
if (CurrentModel.UpdateTime != null)
{
firstModel.Update = time;
}
}
else
{
firstModel.AddTime = new DateTime();
}
ctx.Entry(firstModel).State = System.Data.Entity.EntityState.Modified;
ctx.SaveChanges();
}
Then It will throw:
Why don't I use CurrentModel
to update ? Because firstModel
I change so many property, I don't want to copy all property. I just need to get some info from Database, and replace it then Save.
I already see this:An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key
That way I don't like it. I get confused, and It's Complicated.
I also use trying to another way to fixed it:
// just judge it without get it
if (ctx.Persons.Any( x=> x.Id = 5 && x.UpdateTime != null){
// then do something change after judge
}
Basicly now I know the problem source it : Entity Framework cache the result after get it . That's why after I get a new model, It don't let me use the old.
But I still searching a better and height performance way(I just want less deals with Database) to fix it. Do you have any idea?