Use interface var when calling dbconnection.Insert(..)

When i declare the var as LookupItem, the insert is correct, but when i declare the var as an interface, the ‘wrong’ object is inserted. How can i force the insert command to insert the implementation instead of the interface?

System.Data.SqlClient.SqlException : Invalid object name ‘IEntity’.

using (IDbConnection connection = factory.OpenDbConnection())
            {
                using (IDbTransaction transaction = connection.OpenTransaction())
                {
                    IEntity item = new LookupItem { Code = "Code" };
                    item.Id = connection.Insert(item, true);
                    transaction.Commit();
                }
            }

It needs to be casted it into the type you want to it inserted as.

Ok, but i don’t know the type at runtime:

IList<IEntity> updates;
foreach (IEntity item in updates){
  item.Id = connection.Insert(item, true);
}

OrmLite API’s works with the Type that you give it, if you give it an IEntity that’s what it assumes.

If you’re trying to work with a late-bound Type have a look at the using the Untyped API:

var typedApi = db.CreateTypedApi(item.GetType());

typedApi.Insert(item);
1 Like

Solved! Thanks, mark as closed :wink:

1 Like