更新的EF 4.1纪录 [英] Updating record in EF 4.1

查看:144
本文介绍了更新的EF 4.1纪录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个雇员对象说:

public class Employee
{
    public int Id {get; set;}
    public int Name {get; set;}
    public int Address {get; set;}

 ...other few 10's of properties
}

现在的问题是我怎么只更新名称?对于如。如果我想更新名称怎么办

The question is how do I only update Name? For eg. If I want to update Name I do

Employee e = Db.Employees.Where(e => e.Id == someId).SingleOrDefault();
e.Name = "Jack";
Db.SaveChanges();

正如你所看到的,用于更新我必须先获取对象,然后更新,然后调用调用SaveChanges()。对于一个任务,可以在一个单一的查询进行到数据库中,我有2个疑问火:1)获取对象2)更新所需的对象并保存更改

As you can see, for updating I have to first get the object and then update and then call SaveChanges(). For a task that can be done in a single query to a database I have to fire of 2 queries: 1) Get the object 2) update the required object and save changes.

对于传统的存储过程的方法,我只想通过编号,通过新的名字,写更新语句,我做的。是实体框架真的如此低效的还是我失去了一些东西?

For traditional stored procedure approach I would just pass the Id, pass the new Name and write Update statement and I am done. Is Entity Framework really that inefficient or am I missing something?

推荐答案

您可以选择性地更新列:

You can update columns selectively:

var employee = new Employee() { Id = someId, Name = "Jack" }
Db.Employees.Attach(employee);
Db.Employees.Entry(employee).Property(e => e.Name).IsModified = true;

Db.SaveChanges();

请注意:只有EF 5与.NET 4.5支持设置通过isModified 返回

Note: Only EF 5 with .NET 4.5 supports setting IsModified back to false.

这篇关于更新的EF 4.1纪录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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