Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework inheritance: sort/group by type?

Entity framework (and RIA Services, which I use it with) support inheritance nicely. The database mapping can be single-table or multi-table, and in the first case the database table includes a designator column containing the type designator.

Obviously this designator is not visible in the model, even though it's something one would like to have in order to order by and group over.

Do I have to introduce an additional explicit type designator in the base class if that's what I want to do or is there a nicer way to order or group by the type in some way?

I'm using EF5.

like image 869
John Avatar asked Nov 04 '22 00:11

John


1 Answers

Yes, I can imagine scenarios where you'd want a list of base types. Unfortunately there is no way to get the discriminator (designator) in the conceptual model. The only way I can think of is something like

db.BaseObjects.Where(b => ...)
  .AsEnumerable().Select (b => new {b.GetType().Name, b } )

After that you can sort/group by the type name. But you can't project (Select) before the AsEnumerable, so the only way to restrict the size of the data is by filtering (Where).

There is a trick to get the discriminator column as a visible property in the class model. You can create a computed column in the table, that just displays the value of the real discriminator column, and map it to a property that is marked as DatabaseGeneratedOption.Computed.

Note that this needs special attention with code-first (migrations). And it takes some performance with inserts and updates because EF must read the value from the database afterwards.

like image 59
Gert Arnold Avatar answered Nov 16 '22 12:11

Gert Arnold