1

I have following code for updating user's column

 public void UpdateLastModifiedDate(string username)
        {
            using (AppEntities db = new AppEntities())
            {
                var result = from u in db.Users where (u.UserName == username) select u;

                if (result.Count() != 0)
                {
                    var dbuser = result.First();

                    dbuser.LastModifiedDate = DateTime.Now;
                    db.SaveChanges();
                }
            }
        }

I have other's 2 function of almost same of above function for UpdateLastLogOutDate, UpdateLastLoginDate. So, I decided to define single function for all to update Last Date like:

public void UpdateLastDate(string username, string ColumnName);

Here, I can not put ColumnName variable like this:

dbuser.ColumnName = DateTime.Now;

Is there any other way to do this using LINQ

2 Answers 2

6

You could define the method like this:

public void Update(string username, Action<User> action)
{
    using (AppEntities db = new AppEntities())
    {
        var result = from u in db.Users where (u.UserName == username) select u;

        if (result.Count() != 0)
        {
            var dbuser = result.First();
            action(dbuser);
            db.SaveChanges();
        }
    }
}

And now there could be different usages of this method:

Update("john", user => user.LastModifiedDate = DateTime.Now);                
Update("smith", user => user.UpdateLastLogOutDate = DateTime.Now);
Update("admin", user => 
{
    user.LastModifiedDate = DateTime.Now;
    user.UpdateLastLogOutDate = DateTime.Now;
});

But if the expression is not known at compile time you may take a look at dynamic LINQ.

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

1 Comment

Thanks a lot I have tried it and works perfectly. It helps me to reduce a lot of code. Thanks again
1

You could write your code this way also by sending an instance of your entity as parameter:

public void UpdateLastModifiedDate(Entityclassname ent) //[like if table name is item then Entityclassname should be items etc..]
{   
  using (AppEntities db = new AppEntities())            
  {      
    var result = from u in db.Users where (u.UserName == ent.username) select u;   
    if (result.Count() != 0)         
      {                   
           var dbuser = result.First();        
             dbuser.LastModifiedDate = DateTime.Now; 
             dbuser.UpdateLastLogOutDate=ent.UpdateLastLogOutDate ;
             db.SaveChanges();    
      }
  } 
}

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.