I am using Visual Studio 2012 and Entity Framework 6.0 and I am doing some CRUD
operation but I have some challenge to face now that.
I am doing multiple entries in one form and want to update or save those details at once so I am doing now like this:
Create object and store values and Add / Update by attach one by one and save changes.
But can I do it like attach multiple object of class and do savechanges
at last i mean after for loop. So is it running to save multiple savechanges
by attaching multiple objects?
Example:
for(int i=0; i < comingrequestdata.Count(); i++)
{
ObjectExample obj = new ObjectExampole();
obj.Value1 = comingrequestdata[i].Value1;
obj.Value2 = comingrequestdata[i].Value2;
obj.Value3 = comingrequestdata[i].Value3;
context.ObjectExamples.Attach(obj);
}
context.SaveChanges();
Can I do it like this? I am little bit confused please some one help me.
Adding a new item and updating modified items is not really straightforward as just calling one method. You need to distinguish when you are adding a new item or when you are updating. But yes, you can submit multiple items to be updated or added as new. For example, this method can help you do both adding and updating of an entity:
public SomeEntity AddOrUpdate(SomeEntity item)
{
var original = _context.SomeDbSet.Local.FirstOrDefault(p => p.Id == item.Id)
?? _context.SomeDbSet.FirstOrDefault(p => p.Id == item.Id);
if (original != null) // Updating
{
var entry = _context.Entry(original);
entry.CurrentValues.SetValues(item);
}
else
{
// New item
item = _context.SomeDbSet.Add(item);
}
return item;
}
After a number of calls to this method, call SaveChanges
on your DbContext
-based object.
Thanks for the answer all of you and I have done somehing like this Just create the object of the table I mean class like:
EntityFrameworkEntities db = new EntityFrameworkEntities();
Classname obj = new Classname();
obj.updatefirstvalue = something;
obj.updatesecondvalue = something;
db.Entry(obj).State = EntityState.Modified;
db.SaveChanges();
That's it. and we can also add as more as class we want to update with savechanges at last like:
foreach(var item in collection){
Classname obj = new Classname();
obj1.updatefirstvalue = item.something;
obj1.updatesecondvalue = item.something;
db.Entry(obj).State = EntityState.Modified;
}
db.SaveChanges();