开发者

Can I update multiple columns using LINQ?

I currently am using existing code that has

Sql.Append("UPD开发者_开发问答ATE 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()) +

and it goes on like that for all the columns in the table that it is updating. I would like to know if it would be better using LINQ, easier, more beneficial, and if so how would I go about doing it?

Thanks


For Linq To Entity you can just get all the Store than loop through them to change the value and use the Entity to SaveChanges.

For example:

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();
}

You can do the same with Linq To Sql with the DataContext.

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();
}

But, if you want to be more performance, I think it should be in a stored procedure, this way you won't need to get all the data before updating.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜