1

I want to do the following in LINQ:

update [dbo].[AdminLogin] set [ADMIN_PASSWORD] = 'abc' where [ADMIN_ID] = 1

where i get the admin password from a model and the admin id is stored in a variable:

var userid = (from m in db.RequestPasswordReset
                   where m.Id == Unid
                   select m.UserId).FirstOrDefault();

How to do it?

9
  • are you using EF context? Commented May 3, 2016 at 10:01
  • Linq if for getting/filtering data, not for updating a database Commented May 3, 2016 at 10:01
  • @StephenMuecke I want to update the password of an existing user Commented May 3, 2016 at 10:02
  • Yes, but that's not linq is for. Commented May 3, 2016 at 10:04
  • 1
    You get the object from the context (using a ling query), update its property, mark it as modified and call db.SaveChanges() - Entity states and SaveChanges Commented May 3, 2016 at 10:07

5 Answers 5

4

To update an entity you must have to specify the Modified state.

using (var db= new DbContext())
{
  var entity= db.AdminLogin.Where(x => x.ADMIN_ID == userid ).SingleOrDefault();
  entity.ADMIN_PASSWORD = 'abc';
  db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
  db.SaveChanges();
}

see details here

Sign up to request clarification or add additional context in comments.

3 Comments

I believe you dont need to mark the entity state as modified as Ef will track it for you stackoverflow.com/questions/7106211/… you could omit this line db.Entry(entity).State = System.Data.Entity.EntityState.Modified; EF would do this for you
Setting state manually is important in case of detached entities (entities loaded without change tracking or created outside of the current context). So using Modified means you are always in safe side.
Yes its valid statement, But when you fetch the entity it will be tracked, Hence i believe if you save change by modifying it without marking it will still do a update instead of insert . Correct me if i;m wrong
1

use this code:

using (var context = new YourContext())
{
    var res = context.AdminLogin.Where(x => x.ADMIN_ID == userid ).SingleOrDefault();
    res.ADMIN_PASSWORD = 'abc';
    context.SaveChanges();
}

Comments

1

You can try this:

var user = db.AdminLogin.FirstOrDefault(x => x.ADMIN_ID == id);
user.ADMIN_PASSWORD = 'abc';
db.SaveChanges();

Comments

0
userid.ADMIN_PASSWORD= 'abc';
db.SaveChanges();  //better then db.SubmitChanges() in some case

Comments

0

If you using linQ.dbml file then you have to write like this:

using (var db= new DbContext())
{
  var entity= db.AdminLogin.Where(x => x.ADMIN_ID == userid ).FirstOrDefault();
  entity.ADMIN_PASSWORD = 'abc';

  db.SubmitChanges();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.