簡體   English   中英

使用Dapper更新數據庫

[英]Updating Database Using Dapper

我不知道這在是否可行。 假設我有這個課程:

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 FirstName=@FirstName, LastName=@LastName where Id=@Id";
        Dapper.Execute(sql, student)
    }
}

現在,在調用代碼上,我將得到以下內容:

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

現在,如果我們要更新Student並僅提供IdFirstName ,它將拋出一個錯誤,我也需要提供LastName 我正在尋找一種可以使用的解決方案,即使我未指定Student.LastName ,它仍然會進行更新,並且由於我未指定LastName ,所以Student.LastName將保持不變。

好吧,這是一個快速而骯臟的:

我沒有編譯或測試它,所以可能有錯字

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 FirstName=@FirstName where Id=@Id", student);
else
  Dapper.Execute("Update Student set FirstName=@FirstName, LastName=@LastName where Id=@Id", student);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM