I am new to both asp.net mvc and ormlite. Where should I place the code to create dbFactory? I am not using a container.
What I am doing now works but does not close connections correctly.
I am new to both asp.net mvc and ormlite. Where should I place the code to create dbFactory? I am not using a container.
What I am doing now works but does not close connections correctly.
If you donât want to use a container than you should use a static property to ensure youâre using a singleton instance, a popular approach is to have a static property on your MvcApplication
class, e.g:
public class MvcApplication : System.Web.HttpApplication
{
public static IDbConnectionFactory DbFactory;
protected void Application_Start()
{
DbFactory = new OrmLiteConnectionFactory(
ConfigurationManager.AppSettings["connectionString"],
SqlServerDialect.Provider);
}
}
Then to make using OrmLite easier Iâd use a Base Controller class that has an IDbConnection
property
public abstract class ControllerBase : Controller
{
private IDbConnection db;
public IDbConnection Db => db ?? (db = MvcApplication.DbFactory.OpenDbConnection());
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
db?.Close();
}
}
Which you can use directly in your Controller classes, e.g:
public class MyController : ControllerBase
{
public ActionResult Index()
{
var results = Db.Select<Table>();
}
}
I get an error "Cannot implicitly convert type âServiceStack.OrmLite.OrmLiteConnectionFactoryâ to âSystem.Data.Entity.Infrastructure.IDbConnectionFactoryâ.
If I change DbFactory to type OrmLiteConnectionFactory then the error goes away.
When I try to do the ControllerBase class I get lots of red wigglers.
"Db => db ?? (db =" all with red wigglers + "DbFactory" + "db?.Close"
I appreciate the help greatly.
You need to change it to use the right ServiceStack.Data.IDbConnectionFactory
.
Thanks. That fixed the problem creating DbFactory. Still have the red wigglers in ControllerBase.
Intellisense wants a ; where the lambda operator is. I suspect I may be missing a using but donât know which one.
That uses valid C# 6 syntax, if you want C# 5 syntax change it to:
private IDbConnection db;
public IDbConnection Db
{
get { return db ?? (db = MvcApplication.DbFactory.OpenDbConnection()); }
}
Some of us are still in the Dark Ages! Red wigglers are gone. Thank you very much.