gpt4 book ai didi

c#-4.0 - 当将修改后的实体作为参数传递时,如何更新 EF 实体?

转载 作者:行者123 更新时间:2023-12-02 21:55:02 24 4
gpt4 key购买 nike

我有一个简单的问题。

假设context是我的EF上下文,Respondent是EF从数据库生成的实际EF实体。

更新受访者的最快捷方式是什么?

public void UpdateRespondent(Respondent respondent)
{
var resp = context.Respondents.First(r => r.RespondentId == respondent.RespondentId);

// Now... do I have to copy all properties from the respondent into resp ??
// But respondent is actually the Respondent entity
// Can I just replace it somehow?

context.SaveChanges();
}

非常感谢。

更新1

感谢 nrodic,这段代码就像一个魅力:

public void UpdateRespondent(Respondent changed)
{
var respondent = db.Respondents.FirstOrDefault(r => r.RespondentId == changed.RespondentId);

db.Respondents.ApplyCurrentValues(changed);
db.SaveChanges();
}

有一个问题 - 看起来我根本不需要第一行“varrespondent =”!!

知道为什么在许多例子中出现这条线吗?

谢谢。

更新2

嗯,看来我需要第一行。否则,它会在第二行抛出异常 (db.Respondents.ApplyCurrentValues(changed);)

An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager. Verify that the key values of the supplied object match the key values of the object to which changes must be applied.

enter image description here

最佳答案

你可以这样做:

    public void UpdateRespondent(Respondent respondent)
{
var resp = context.Respondents.First(r => r.RespondentId == respondentId);

// Now... do I have to copy all properties from the respondent into resp ??
// But respondent is actually the Respondent entity
// Can I just replace it somehow?

resp.Name = "Bob";
resp.SomeProperty = "SomeValue";
context.SaveChanges();
}

您只需更新 resp 对象的属性即可。尽管看到第一条评论,但它可能并不完全是您想要的。

关于c#-4.0 - 当将修改后的实体作为参数传递时,如何更新 EF 实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14506520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com