1

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

 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,我有其他2个与上述功能几乎相同的功能。因此,我决定为所有人定义单个函数来更新 Last Date,例如:

public void UpdateLastDate(string username, string ColumnName);

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

dbuser.ColumnName = DateTime.Now;

有没有其他方法可以使用 LINQ

4

2 回答 2

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

但是,如果在编译时不知道表达式,您可以查看动态 LINQ

于 2012-06-21T08:05:29.620 回答
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();    
      }
  } 
}
于 2012-10-11T01:02:11.630 回答