c# - 如何在 Entity Framework 中编辑对象?

标签 c# entity-framework ado.net

DataContext.ApplyCurrentValues() 需要 entitySetName,它是什么?

我认为代码会相同:

    public void Edit(Products p)
    {
        DataContext.ApplyCurrentValues("Products", p);
        DataContext.SaveChanges();
    }

是否正确?

最佳答案

这是 .Net 4.0

对于这个例子,假设我们正在处理 Product 对象。

using (DBEntities context = new DBEntities())
{
    //Must attach first and change the state to modified
    context.Products.Attach(product);

    //If you are using .Net 4.1 then you can use this line instead:
    //context.Entry(
    context.ObjectStateManager.ChangeObjectState(product, EntityState.Modified);

    context.SaveChanges();
}

如果您使用的是 .Net 4.1,则可以使用“context.Entry(...)”代替“context.ObjectStateManager.ChangeObjectState(product, EntityState.Modified)”,如下所示: Example of context.Entry()

这是最直接的方法。它不需要您先从数据库中提取对象,您只需提供您正在修改的对象即可。唯一的缺点是这会更新所有字段,而不仅仅是单个字段。

关于c# - 如何在 Entity Framework 中编辑对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5014347/

相关文章:

c# - 如何在现有的 AspNetUsers 表中添加一列

c# - 如何删除 Entity Framework Core 2.0 中的特定迁移?

c# - 运行时数据库的 SQL 与 Entity Framework

asp.net - 访问 2007 的连接字符串

entity-framework - ADO.NET Entity Framework 数据库架构更新可能吗?

c# - 反射(reflection)动态类型以判断它是否是动态类型,首先

c# - 组合或连接从单独的 XML 文件中读取的对象的最有效方法

c# - response.redirect 不起作用

c# - SqlConnection 是如何管理 IsolationLevel 的?

c# - 在 Redis C# 中批量创建键 - SocketException : Only one usage of each socket address (protocol/network address/port) is normally permitted