![](/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.