我可以使用LINQ更新多个列吗?

时间:2011-10-13 14:38:47

标签: c# linq

我目前正在使用

的现有代码
Sql.Append("UPDATE Store SET" +
"LogoAlign='" + (String.Compare(drpLogoAlign.SelectedValue, String.Empty) == 0 ? "NULL" : "'" + drpLogoAlign.SelectedValue + "'") +
"', Height='" + DB.QuerySafeDisplayHTML(txtHeight.Text.ToString()) +
"', Width='" + DB.QuerySafeDisplayHTML(txtWidth.Text.ToString()) +

对于正在更新的表中的所有列,它会继续下去。我想知道使用LINQ是否更好,更容易,更有益,如果是这样我将如何去做呢?

谢谢

1 个答案:

答案 0 :(得分:0)

对于Linq To Entity,您可以获取所有Store而不是循环遍历它们以更改值并将实体用于SaveChanges

例如:

using (TestDBEntities ctx = new TestDBEntities())
{
    var allStore = ctx.Stores;
    foreach(var store in allStore)
    {
        store.LogoAlign = (String.Compare(drpLogoAlign.SelectedValue, String.Empty) == 0 ? "NULL" : "'" + drpLogoAlign.SelectedValue + "'");
        store.Height = txtHeight.Text.ToString();
    }
    ctx.SaveChanges();
}

您可以使用DataContext对Linq To Sql执行相同的操作。

using (TestDataContext ctx = new TestDataContext())
{
    var allStore = ctx.Stores;
    foreach(var store in allStore)
    {
        store.LogoAlign = (String.Compare(drpLogoAlign.SelectedValue, String.Empty) == 0 ? "NULL" : "'" + drpLogoAlign.SelectedValue + "'");
        store.Height = txtHeight.Text.ToString();
    }
    ctx.SubmitChanges();
}

但是,如果你想提高性能,我认为它应该是 stored procedure ,这样你就不需要在更新之前获取所有数据。