gpt4 book ai didi

c# - 如何使用 LINQ to SQL 设置整个对象?

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

因此,如果想要使用接收到的具有相同 PK 的对象中的值来更新数据库中的一行,我们该怎么做。需要这样做的原因是因为对象非常广泛,这将创建另一个地方,如果我们更新数据库,我们必须在其中更改字段名称。所以我的问题是如何将一个对象分配给使用 LINQ 从数据库检索的对象?我将展示我正在谈论的内容以澄清。

//Foo Object Received up here, called RecFoo
using (var newContext = new FooDataContext())
{
var obj = newContext.T_Foo.Single(x=>x.Id == RecFoo.id);
//Set obj = recFoo (Directly)
newContext.SubmitChanges();
}

我知道我们可以设置每个单独的属性(obj.Name = RecFoo.Name...),但是有什么方法可以让我们使用 PK id 获取接收到的对象并为其分配内部的所有值RecFoo?

编辑:解决方案

    using (var newContext = new FooDataContext())
{
//var obj = newContext.T_Foo.Single(x=>x.Id == RecFoo.id);
//Set obj = recFoo (Directly)
newContext.T_Foo.Attach(recFoo);
newContext.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, recFoo);

newContext.SubmitChanges();
}

最佳答案

您尝试过newContext.YourEntity.Attach(YourAlreadyPopulatedObject)

在此,您只需告诉 Linqtosql 该记录已存在于数据库中并且您正在更新它。

关于c# - 如何使用 LINQ to SQL 设置整个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18407079/

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