2016-11-30 18 views
0

でこれが可能かどうかわかりません。 のは、私はこのクラスを持っているとしましょう:私たちはStudentを更新してのみIdを提供しようとしている場合は、今すぐDapperを使用したデータベースの更新

Student student=new Student(); 
student.Id=1; 
student.FirstName="abc"; 
student.UpdateStudent(student); 

public class Student 
{ 
    public int Id{get;set;} 
    public string FirstName{get;set;} 
    public string LastName{get;set;} 

    public int UpdateStudent(Student student) 
    { 
     string sql="Update Student set [email protected], [email protected] where [email protected]"; 
     Dapper.Execute(sql, student) 
    } 
} 

は今、呼び出し元のコードに、私はこのような何かを持っていますFirstNameと入力すると、LastNameも入力する必要があるというエラーが表示されます。私はStudent.LastNameを指定していなくても更新を行い、LastNameを指定していないので、Student.LastNameは同じままであることができる解決策を探しています。ここ

+1

あなたの質問が何であるか全く分かりません。 – Hogan

+0

混乱して申し訳ありません。私は質問を編集してみんなに分かりやすくします。 –

+0

IF文を使用する必要があります – Hogan

答えて

0

OK]をクリックして迅速かつ汚いです:

それはタイプミス

public static void UpdateFromItem(string tableName, object updatevalues, object selectorvalue) 
    { 
    string updateStr=new String(); 
    string whereStr=new String(); 

    foreach (PropertyInfo prop in updatevalues.GetType().GetProperties()) 
    { 
     if (prop.GetValue(parms, null) != null) 
      updateStr.AppendFormat(" %s=%s",prop.Name, prop.GetValue(parms, null)); 
    } 

    foreach (PropertyInfo prop in selectorvalues.GetType().GetProperties()) 
    { 
     if (prop.GetValue(parms, null) != null) 
      updateStr.AppendFormat(" %s=%s",prop.Name, prop.GetValue(parms, null)); 
    } 


    string sqlStmt=string.Format(@"UPDATE %s SET %s WHERE %s",tableName, updateStr,wherreStr); 

    Drapper.Execute(sqlStmt); 
    } 

この

UpdateFromItem("Student", new { FirstName : "abc"}, new { Id : 1 }); 
のようにそれを呼び出している場合がありますので、私はこれをコンパイルするか、テストしていません

私は上記の一般的なソリューションを作った、あなたはまた、学生オブジェクトのidフィールドについて、具体的にこのような解決策はうまくいくでしょう:

public static void UpdateStudent(Student inobj) 
    { 
    string updateStr=new String(); 
    string whereStr=string.Format(@"Id=%s",inobj.Id); 

    foreach (PropertyInfo prop in inobj.GetType().GetProperties()) 
    { 
     if ((prop.GetValue(parms, null) != null) && (prop.Name != 'Id')) 
      updateStr.AppendFormat(" %s=%s",prop.Name, prop.GetValue(parms, null)); 
    } 

    string sqlStmt=string.Format(@"UPDATE %s SET %s WHERE %s",tableName, updateStr,wherreStr); 

    Drapper.Execute(sqlStmt); 
    } 

人々は、これは注射リスクがあることを指摘します。それはパラメータリストを作成することで解決できますが、あなたはその考えを得ると思います。基本的にはループが必要です。



これはあなたが必要となります難しいことではありませんif文、このような何か:

if (student.lastName.IsNullOrEmpty()) 
    Dapper.Execute("Update Student set [email protected] where [email protected]", student); 
else 
    Dapper.Execute("Update Student set [email protected], [email protected] where [email protected]", student); 
+0

そうですが、私のデータベースに多数のカラムがあるので、それは私のためにもっと多くの仕事になります:D –

+0

@DikongPrigmあなたはオブジェクトフィールドと変更を見る "自動"ルーチンその内容に基づいた更新ステートメントあなたは私にそれをする方法を示す必要がありますか? – Hogan

+0

私は例があるのが大好きです。 –

関連する問題