Sumedha Vangury
Sumedha Vangury

Reputation: 673

how to update a record in database using LINQ?

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?

Upvotes: 1

Views: 4252

Answers (5)

Kinjal Gohil
Kinjal Gohil

Reputation: 968

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

Upvotes: 0

S.Bozzoni
S.Bozzoni

Reputation: 1002

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

Upvotes: 0

Mahbubur Rahman Manik
Mahbubur Rahman Manik

Reputation: 5161

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

Upvotes: 4

Amine
Amine

Reputation: 1336

You can try this:

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

Upvotes: 1

Karthik M R
Karthik M R

Reputation: 990

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

Upvotes: 1

Related Questions