![](/img/trans.png)
[英]Updating an Informix database over ODBC with an object using Dapper
[英]Updating Database Using Dapper
我不知道這在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
並僅提供Id
和FirstName
,它將拋出一個錯誤,我也需要提供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.