如何使用LINQ到SQL更新? [英] How to update with Linq-To-SQL?

查看:125
本文介绍了如何使用LINQ到SQL更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更新的价值观,但我是循环所有的表值做到这一点:

I need to update values but I am looping all the tables values to do it:

public static void Update(IEnumerable<Sample> samples
    , DataClassesDataContext db)
{
    foreach (var sample in db.Samples)
    {
        var matches = samples.Where(a => a.Id == sample.Id);
        if(matches.Any())
        {
            var match = matches.First();
            match.SomeColumn = sample.SomeColumn;
        }
    }
    db.SubmitChanges();
}

我敢肯定的code以上是不正确的方式来做到这一点,但我想不出任何其他方式呢。你能表现出更好的办法吗?

I am certain the code above isn't the right way to do it, but I couldn't think of any other way yet. Can you show a better way?

推荐答案

是的,有一个简单的方法。简单得多。如果您将实体的上下文,然后刷新(与选定KeepCurrentValues​​),LINQ到SQL将获得这些实体的服务器,对它们进行比较,并标记更新的那些不同。您的code会是这个样子。

Yes, there is a simpler way. Much simpler. If you attach your entities to the context and then Refresh (with KeepCurrentValues selected), Linq to SQL will get those entities from the server, compare them, and mark updated those that are different. Your code would look something like this.

public static void Update(IEnumerable<Sample> samples
    , DataClassesDataContext db)
{
    db.Samples.AttachAll(samples);
    db.Refresh(RefreshMode.KeepCurrentValues, samples)
    db.SubmitChanges();
}

在这种情况下,LINQ to SQL中使用的按键来匹配和更新记录,这样,只要你的钥匙都在同步,你的罚款。

In this case, Linq to SQL is using the keys to match and update records so as long as your keys are in synch, you're fine.

这篇关于如何使用LINQ到SQL更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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