开发者

EntityFramework 4.0: can you return different types depending on data in the database?

开发者 https://www.devze.com 2022-12-28 23:09 出处:网络
I have a Media table in the database. I also have an IMedia interface. I have two different media types that implements th开发者_高级运维e same interface:

I have a Media table in the database. I also have an IMedia interface.

I have two different media types that implements th开发者_高级运维e same interface:

1) AudioMedia

2) PictureMedia

What I wonder here, is if I can use EntityFramework (I'm using an EDMX file but I have my models in a separate library, with automatic code generation turned off), and depending on the data in the database, select what type to get (AutioMedia or PictureMedia).

Since they are both implementing the same interface (could be changed to an abstract class if needed I suppose), I'm thinking that somewhere along the way you could specify what class it should be.

I should perhaps point out that I have a class that inherits from ObjectContext to access the objects. Perhaps there is something that that can be done?


Do you have a common ID field?

Take a look at

http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/09/30/how-to-model-inheritance-in-databases.aspx

and

http://blogs.msdn.com/alexj/archive/2009/04/15/tip-12-choosing-an-inheritance-strategy.aspx?CommentPosted=true#commentmessage

Changing it to an Abstract base class would almost certainly make it easier to model using Entity Framework.


You can use inheritance : both AudioMedia and PictureMedia would inherit from a common MediaBase abstract class, represented by a table. The members specific to AudioMedia and PictureMedia would be stored in separate tables.

This technique is called the "table per type" strategy, and is supported by the Entity Model designer.

You could also use the "table per concrete type" strategy, but I don't think it is supported by the designer (however it is supported by Entity Framework)

Check this link for details : http://blogs.msdn.com/adonet/archive/2007/03/15/inheritance-in-the-entity-framework.aspx

0

精彩评论

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

关注公众号