Best way to share "Db" all over POCO classes


I am trying to implement a project to give POCO’s to insert/update/delete instance method capabilities.
I mean, I do not want to use OrmLite as;

Employee emp = new Employee();
using (var db = dbFactory.Open())
   emp.Name = "Ali";
   emp.SurName = "Veli";

Instead of doing this, I just want to

Employee emp = new Employee();
emp.Name = "Ali";
emp.SurName = "Veli";

And also create queries like

Employee emp = new Employee();
var results = emp.Select(emp.From().Where(x=>x.Name == "Ali"));

I know those are not hard to do things, if the POCO’s have Db connections on their instance like ServiceStack Services.
What is the best way of sharing Db in POCO classes? (Injection or something else ? )

I think I found a simple answer, I do not know if it is best, but it works.

        private IDbConnection db;
        public virtual IDbConnection Db
            get {
                return db ?? (db = HostContext.AppHost.GetDbConnection());

Sorry for the question garbage .

It’s no longer a POCO if it contains a DB connection, you’ve also just limited the reusability of the model to DB persistence, you now have to be careful that you didn’t break serialization and have to make sure your disposing resources properly.

Overall I think it’s a bad idea for models to contain managed resources and would recommend against it.

Also when you’re in a Service you don’t need to open a new DB Connection, you can just access it with:


ServiceStack takes care of opening the new connection on first access and disposing after Service has been executed.

Your other dependencies can inherit RepositoryBase which provides a similar UX for accessing the DB connection outside of your Services.

But if I will use DB.Insert style, I won’t be able to write methods like “beforeInsert” and “afterInsert” easily.

I am developing an ERP project, and it is a must.

Do you have any other suggestion to accomplish this?

You can use Update/Insert filters on OrmLite to fire callbacks when each model gets saved. You can also call your own custom Insert extension method off IDbConnection which executes custom logic before calling OrmLite. Anything but couple your models to a DB Connection.

More info that helped me with this from this post:
StackOverflow article for OrmLite filters

Thank you Rob and mythz,
But this is not fits my need.
Because I need, both before and after methods. This only gives me before event.
And also there is no before/after delete methods.