2

因此,如果想使用具有相同 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();
}
4

1 回答 1

5

你有没有尝试过newContext.YourEntity.Attach(YourAlreadyPopulatedObject)

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

于 2013-08-23T16:01:05.993 回答