简体   繁体   中英

How to write update query using linq to sql in where condition having two column names in c#?

I want to update one column in sql.in where condition two column names are there.

below is mu update query:

  string sql = "UPDATE contact set ContactName=@ContactName where ContactID=@ContactId AND UserID=@Userid";

now I want to write using linq.How to write above query using linq.please help me.I tried

  var updatequery = (from x in obj.Contacts where x.ContactID == ContactID select x).First();

                  updatequery.ContactName = ContactName;
                  obj.SubmitChanges();

but in the above query where condition having only one column name.I want to where condition having two column names.Thanks in advance.

You just have to use the conditional-AND operator && :

var updateContacts = from x in obj.Contacts 
                  where x.ContactID == ContactID && x.SecondColumn == SecondValue 
                  select x;

// now use First or a loop if you expect multiple
foreach(var contact in updateContacts)
    contact.ContactName = ContactName;
obj.SubmitChanges();

I don't know if this will help but you can try this as well.

var updatequery = obj.Contacts
              .Where(x => x.ContactID == ContactID && x.SecondColumn == SecondValue)
              .FirstOrDefault();
updatequery.ContactName = ContactName;
obj.SubmitChanges();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM