Inheritance and Dapper.net

dapper

Question

I decided to use Dapper.net because it seems to be doing only what I want : mapping, I don't need anything fancy , I'm just bored to handle the mapping between my datareader and my object.

My problem :

Let's say I have these class :

class Foo{
int ID;
string Name;
}
class Bar : Foo{
string FavoriteMoovie;
}

And these tables :

Foo 
- ID
- Name

Bar
- FooID
- FavoriteMoovie

So I'd like to know how I can select my Foo and Bars in the same query ?

My only idea so far is

  • SELECT all the Foos that are not Bars
  • then SELECT all the Bars

I can't use the overload of the method "Query" because there are just here for mapping relationships.

Popular Answer

Very hacky, but this probably works.

db.Query<Bar, object, Foo>("select * from Foo left join Bar on FooID = ID",
 (bar,ignore) => 
   bar.FavoriteMoovie == null ? bar : new Foo{ID = bar.ID, Name = bar.Name});

Disadvantage is that it creates a couple of intermediate objects that it could do without.

Other options are to simply select Bar objects and then use the same trick to filter out the Foos or select a dynamic and then convert to the correct class.

Personally I would not query twice just to handle this, unless you are allowing for NULL FavoriteMoovie, in which case you have no choice but to either complicate the query or select twice.




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