使用实体框架修改字段而不使用EntityObject [英] Modify field with Entity Framework without EntityObject

查看:99
本文介绍了使用实体框架修改字段而不使用EntityObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子是一张照片和其他文件类型的表格。我想编辑名称字段。通常我会这样做:

  var file = Db.Files.First(f => f.FileID == id) ; 
file.Name =NewName;
Db.SaveChanges();

但是,在这种情况下,这将无需任何理由从数据库服务器提取整个varbinary(max) 。有没有办法编辑一个项目,而不会得到整个EntityObject?也许我可以使用存根实体或东西?

解决方案

你也可以使用这个简单的技巧:

  //定义一个虚拟对象
var file = new File {Id = id,Name =NewName};
//虚拟对象附加为不变实体
context.Files.Attach(file);
//获取有关实体的更改跟踪信息
ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(file);
//将Name属性设置为修改
entry.SetModifiedProperty(Name);
//保存更改 - 只有Name属性将被修改
context.SaveChanges();

它将保存您对数据库的查询。


I have a table which is a table of pictures and other file types. I want to edit the name field. Normally I would do this:

var file = Db.Files.First(f => f.FileID == id);
file.Name = "NewName";
Db.SaveChanges();

However, in this case this will pull the entire varbinary(max) from the database server for no reason. Is there a way to edit an item without getting the entire EntityObject? Perhaps I can use stub entities or something?

解决方案

You can also use this simple trick:

// Define a dummy object
var file = new File { Id = id, Name = "NewName" }; 
// The dummy object attached as Unchanged entity 
context.Files.Attach(file);  
// Get change tracking information about the entity
ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(file);
// Set Name property to modified
entry.SetModifiedProperty("Name");
// Save changes - only Name property will be modified
context.SaveChanges();

It will save you a query to the database.

这篇关于使用实体框架修改字段而不使用EntityObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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