实体框架偏载 [英] Entity Framework partial load

查看:122
本文介绍了实体框架偏载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的表


  • ID(INT)

  • 名称下面列( nvarchar的)通常< 100个字符

  • 数据(nvarchar的)平均1MB

我在写一个程序,通过每一行和执行某些操作名称字段。由于我只使用名称字段和数据字段是非常大的,有可能直接EF只加载Id和Name字段?

I'm writing a program that will go through each row and perform some operations to the Name field. Since I'm only using the Name field and the Data field is very large, is it possible to direct EF to only load the Id and Name field?

推荐答案

肯定是

ctx.YourDbSet.Select(p=> new { Id = p.Id, Name = p.Name});

这方法是选择到一个匿名类。

this method is selecting into an anonymous class.

如果你想再次保存该回你可以用我称之为一个虚拟实体的东西做到这一点:

if you want to save this back again you can do this with something which I call a dummy entity:

foreach(var thing in ctx.YourDbSet.Select(p=> new { Id = p.Id, Name = p.Name}))
{
    var dummy = new YourEntity{Id = thing.Id};
    ctx.YourDbSet.Attach(dummy);
    dummy.Name = thing.Name + "_";
}
ctx.SaveChanges();



此方法适用于快照跟踪为EF只跟踪后所做的更改附加打电话发回了UPDATE语句。这意味着你的查询将只包含在该实体名称属性的更新(即它不会碰的数据)

This method works with snapshot tracking as EF only tracks changes made after the attach call to send back in the update statement. This means your query will only contain an update for the name property on that entity (ie it wont touch data)

请注意:你要确保你这样做对上下文你严格控制,你不能附加上已经连接到EF追踪图形对象。在上述情况下选择将不可以连接实体图形作为其匿名(所以你是使用相同的情况下安全)

NOTE: you want to make sure you do this on a context you tightly control as you cant attach an object which is already attached to the EF tracking graph. In the above case the select will not attach entities to the graph as its anonymous (so you are safe using the same context)

这篇关于实体框架偏载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆