Can we attach more than one object in entity framework and do savechanges once

c# entity-framework entity-framework-6 updates

Question

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.

1
0
8/29/2016 7:47:30 AM

Accepted Answer

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.

2
8/29/2016 8:12:35 AM

Popular Answer

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();


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow