如何更新现有的断开连接的实体 [英] How to Update Existing Disconnected Entity

查看:73
本文介绍了如何更新现有的断开连接的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以在EntityFrameworkCore中使用。

I have this code which works in EntityFrameworkCore.

public void SaveProject(Project item)
    {
        var existing = _context.Projects.FirstOrDefault(a => a.Id == item.Id);
        existing.Description = item.Description;
        existing.IsArchived = item.IsArchived;
        existing.IsDeleted = item.IsDeleted;
        existing.Name = item.Name;
        _context.SaveChanges();

    }

它获取一个断开连接的实体,并在数据库中找到它,并应用更改。

It taking a disconnected entity, finding it in the database, and applying the changes.

还有更好的方法吗?

我不想这样做调用数据库。换句话说,我希望能够将实体标记为已修改,然后调用SaveChanges()。

I would like to not make a call to the database. In other words, I would like to be able to mark the entity as modified, and then call SaveChanges().

有没有办法做到这一点?

Is there a way to do that?

推荐答案

如果确定数据库中存在该项目,则可以使用DbContext的Attach方法,如下所示:

If you are certain that item exist in database, you can use Attach method of DbContext As following

public void SaveProject(Project item)
{
    _context.Projects.Attach(item);
    _context.Entity(item).State=EntityState.Modified;
    _context.SaveChanges();
}

这篇关于如何更新现有的断开连接的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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