在asp.net mvc 3中使用LINQ update特定列

时间:2012-06-21 07:54:37

标签: asp.net-mvc-3 linq-to-sql

我有以下用于更新用户列的代码

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

对于UpdateLastLogOutDate,UpdateLastLoginDate,我有其他两个函数几乎与上面的函数相同。所以,我决定为所有人定义单个函数来更新Last Date,如:

public void UpdateLastDate(string username, string ColumnName);

在这里,我不能像这样放置ColumnName变量:

dbuser.ColumnName = DateTime.Now;

使用LINQ

还有其他方法吗?

2 个答案:

答案 0 :(得分:6)

您可以像这样定义方法:

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

现在这种方法有不同的用法:

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

但如果在编译时未知表达式,您可以查看dynamic LINQ

答案 1 :(得分:1)

您也可以通过发送实体实例作为参数来编写代码:

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