我正在尝试使用Dapper.Contrib.Extensions库将“ClassName”类的实例插入到数据库中,由于我只有纯文本的类名,因此我使用.NET Framework 4.6.1的Activator.CreateInstance方法来创建对象。
强制转换ClassName能够正常工作connTo.Insert((ClassName)instance);,但我不能使用这种方式,因为“ClassName”只是我从XML文件中获取的文本。
private void InsertByDapper(string className, SqlConnection conn)
{
Type type = Type.GetType(className);
if (type != null)
{
var instance = Activator.CreateInstance(type);
// ... update some properties in the instance object...
conn.Insert(instance);
//connTo.Insert((ClassName)instance); //This statment works
}
}
在.NET中抛出异常:System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
错误的解释:Dapper试图将对象插入到Objects表中,但我的目的是将其插入到className表中。
SQL错误:insert into Objects () values ();select SCOPE_IDENTITY() id