开发者

How to introduce polymorphism to Entity Data Model

I am working with a database model that has following tables:

  • Motorcycles,
  • Cars,
  • Planes

When I generate ADO.NET Entity Data Modeledmx file, I get a separate C# class for every table. All of aforementioned classes share the same properties (like MaxSpeed). I would like to introduce a polimorphism, by creating a Vehicle base class, and port common properties and methods to this base class.

I cannot change database, because it does not support inh开发者_StackOverflow社区eritance. Is there a way to achieve this?

I use .NET 4.0 and SQL Server 2008.


If you really can't change your database, then table per concrete class inheritance is what you'd have to do, but that's tricky.

Leniency has provided this example of it in action, which seems really good. One problem with table per concrete type in general is that each of your concrete types—car, plane, motorcycle—each have to have unique keys. In other words, if there's a car with id = 5, then there can be no motorcycle or plane with that id. So with three tables you'd probably have to either use guids, or, as Ladislav pointed out, set your seed and increment values appropriately on your identity columns (seed = 1, 2, and 3, increment = 3)

Ideally you'd want to (change your database and) add a new table with your common properties, and let that serve as your base class, with vehicle, car, etc all inheriting that. EF supports that method—called table per hierarchy—much more easily.


If you do in your way, then you will mess up the POCOs with domain objects unless you apply the code first model driven design in EF 4.1.


Closest you can get is to use Table-per-entity approach.

But then there would need to be Vehicle table, that would store IDs and common properties. This makes a question : How are your IDs stored? Does every table have its own id? Then I think it is impossible to use entity hiearchy. If you can change this, then using Table-per-entity becomes possible.


You may be better off using interfaces to provide access to your entities. Entity code is auto generated so you should not be suffering too much repeated code and you can write methods that will use the interface to treat the classes in a common manner.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜