使用Linq查询更新不能正常工作

本文关键字:工作 常工作 Linq 查询 更新 不能 使用 | 更新日期: 2023-09-27 18:01:33

我是Linq查询的新手,我从多个文本框中获取用户参数以更新数据库中的特定用户,但它不起作用,我尝试了多种方法,但它们不起作用,没有错误,但也没有更新用户

代码:

public void Update(UserEntity person)
{
    UserEntity user = new UserEntity();
    SurveyEntities dbcontext = new SurveyEntities();
    var query = (from p in dbcontext.Users
                 where p.UserId == person.UserId
                 select new UserEntity() { UserId =p.UserId , FirstName = p.FirstName, LastName = p.LastName, Birth = p.Birth.Value, Password = p.Password, UserName = p.Username, Email = p.Email, Active = p.Active.Value }).SingleOrDefault();
    query.FirstName = person.FirstName;
    query.LastName = person.LastName;
    query.UserName = person.UserName;
    query.Password = person.Password;
    query.Email = person.Email;
    query.Birth = person.Birth;
    query.Active = person.Active;
    try
    {
        dbcontext.SaveChanges();
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        // Provide for exceptions.
    }
}

使用Linq查询更新不能正常工作

当你做select new时,你只是尝试更新一个投影。相反,你应该这样写:

var query = (from p in dbcontext.Users
                 where p.UserId == person.UserId
                 select p).SingleOrDefault();

休息应该没问题。

*编辑:有关投影操作(c#)的更多信息和更清晰的想法,您可以参考:

https://msdn.microsoft.com/en-us/library/mt693038.aspx

试试这个

可以使用上下文对象和更新值保存在数据库中。

    public void Update(UserEntity person)
        {
            UserEntity user = new UserEntity();
            SurveyEntities dbcontext = new SurveyEntities();
          //  var query = (from p in dbcontext.Users
          //               where p.UserId == person.UserId
         //                select new UserEntity() { UserId =p.UserId , FirstName = p.FirstName, LastName = p.LastName, Birth = p.Birth.Value, Password = p.Password, UserName = p.Username, Email = p.Email, Active = p.Active.Value }).SingleOrDefault();
  UserEntity tmp=  dbcontext.UserEntity.where(x=>x.userId==person.UserId).FirstDefault();
                tmp.FirstName = person.FirstName;
                tmp.LastName = person.LastName;
                tmp.UserName = person.UserName;
                tmp.Password = person.Password;
                tmp.Email = person.Email;
                tmp.Birth = person.Birth;
                tmp.Active = person.Active;

            try
            {
                dbcontext.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                // Provide for exceptions.
            }

        }