简体   繁体   中英

Using Entity Framework to Select Only Some Columns and then Saving Back to the Database

I want to update a sequence (SortOrder) column in my database using Entity Framework.

Seems like the easiest way is to load the SortOrder for each item in the set, update the SortOrder as needed, and then save the rows back to the database.

Of course, this would be more efficient if I don't need to retrieve every column in the rows I am updating. And what I'm having trouble understanding is what happens if I only select some of the columns, make changes to those columns, and save it back.

var x = from o in Package.PackageProducts
        orderby o.SortOrder
        select new { o.Id, o.SortOrder };
// Modify SortOrder in this collection x
// Save x back to the database

How does Entity Framework handle modifying and saving partial entities like this?

Does anyone know if Microsoft has documented somewhere what happens in this case? Does anyone know enough about what happens that you can tell me?

You can create stub entities from the anonymous types and mark SortOrder as modified:

var x = (from o in Package.PackageProducts
        orderby o.SortOrder
        select new { o.Id, o.SortOrder }).ToList();
// Modify SortOrder in this collection x
...
// Save x back to the database
foreach(y in x)
{
    var p = new PackageProduct { Id = y.Id, SortOrder = y.SortOrder }); // stub
    db.PackageProducts.Attach(p);
    db.Entry(p).Property(p1 => p1.SortOrder).Modified = true;
}
db.SaveChanges();

Where db is the DbContext .

You may have to disable validation first, because the stubs probably don't have all required properties:

db.Configuration.ValidateOnSaveEnabled = false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM