DbContext, DbSet etc in Dapper

c# dapper sql

Question

I'm working on implementing all data access with dapper. My first idea was to implement repository pattern using dapper. from : http://www.bradoncode.com/blog/2012/12/creating-data-repository-using-dapper.html

Then I added linq expression to the dapper sqlbuilder to minimize SQL, like in the example (dynamic query). So I was able to write something like

sqlbuilder.Where(c=>c.Id == 1) or c.Id = myVar

And now i'm asking myself if it would be a good idea to implement a DbContext like and DbSet and use linq expression.

The question is not to implement a complete dbset or dbcontext. But just something that looks like (without all the complexity).

Just a DbContext wich initialize connection and multiple DbSet wich queries tables using Dapper and an implementation of iqueryable to "generate" SQL based on given link expression using dapper sqlbuilder.

After reading some pieces of code and comparing with entity framework, i think it is a waste of time because entity framework already do it. But with dapper you have the entire control of the generated sql and it would always use the same template.

Before starting (to waste my time) I would like to know if it is a good idea or not.

Edit : many comments says that SqlBuider is not a good thing, then why is it available in Dapper project ?

Accepted Answer

Personally I would say that it is something that is outside the core of what the dapper library attempt to offer. There is merit in the idea, but I worry that by the time you've done that, yoouve basically just re-implemented LINQ-to-SQL. There's an easier way to do that: you just use LINQ-to-SQL. Dapper is usually very happy to populate L2S models - that is essentially how we (the dapper authors) used it (and continue to use it) against our pre-existing L2S codebase. It would also be similar to EF etc.

However, if you really want to out the work in, I'm sure you could write a library on top of dapper that does this. It just seems like a lot of work to do things that already exist.


Popular Answer

A key feature of Dapper is performance.

Dapper was created to quickly map results from plain SQL to objects. And definitely not for letting developers to avoid writing SQL. It is probably not good idea to use SQL builder with Dapper. And even worse idea is implementing change tracking. Just use Entity Framework or another full blown ORM if you need such features.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why