简体   繁体   中英

How to instanciate an object by Activator.CreateInstance an inserting it on a table using Dapper

I'm trying to insert an instance of a "ClassName" class in the database using Dapper.Contrib.Extensions library, I am using method of the .NET Framework 4.6.1 because I just have the Class Name in text plain so I can not instanciate an object calling directly to the class. 方法,因为我只是在文本中具有类名称所以我无法实现一个直接调用该类的对象。

Casting the ClassName works as expected connTo.Insert((ClassName)instance); but I can not use this way because "ClassName" is just a text I get from an XML file.

   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
        }
    }

Exception thrown in .NET:

Explanation of the error: Dapper is trying to insert the object in the Objects table. My purpose is to insert it on the className table.

SQL Error: insert into Objects () values ();select SCOPE_IDENTITY() id

I'm guessing you are using a generic method that takes generic argument TEntity or similar. Since you supply it with type object it will use that. There is probably a none generic method you should use.

edit: Yepp, my guess was right.

https://github.com/StackExchange/Dapper/blob/master/Dapper.Contrib/SqlMapperExtensions.cs#L332

And funny enough there is no none generic overload of the method. You can use reflection to invoke the generic method with the correct generic argument

Example, make sure to cache result from MakeGenericMethod , its expensive

typeof(SqlMapperExtensions).GetMethod(nameof(SqlMapperExtensions.Insert)).MakeGenericMethod(instance.GetType()).Invoke(null, new object[] { conn,  instance, null, null});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM