2016-08-09 11 views
0

私はLinqクエリで新しく、複数のテキストボックスから自分のユーザパラメータを取得してデータベース内の特定のユーザを更新しますが、動作しません。複数の方法で試しましたが、また、そこにユーザーの更新なし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. 
    } 
} 
+2

の代わりに、新しいUserEntityを選択するだけのpを選択 - あなたは – NDJ

答えて

1

あなたはちょうどあなたが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

+0

はあなたの助けをありがとう更新するエンティティを持っています –

0

このよう

を試してみてくださいあなたはコンテキストオブジェクトと更新値を使用することができますデータベースに保存する。

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. 
      } 


     } 
関連する問題