简体   繁体   English

使用实体框架仅选择一些列,然后保存回数据库

[英]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. 我想使用实体框架更新数据库中的序列(SortOrder)列。

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. 似乎最简单的方法是为集合中的每个项目加载SortOrder,根据需要更新SortOrder,然后将行保存回数据库。

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: 您可以从匿名类型创建存根实体,并将SortOrder标记为已修改:

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 . 其中dbDbContext

You may have to disable validation first, because the stubs probably don't have all required properties: 您可能必须先禁用验证,因为存根可能没有所有必需的属性:

db.Configuration.ValidateOnSaveEnabled = false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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