abend
abend

Reputation: 483

default vs custom using entity framework

I've got a table of default templates. It's global to all users. If a user has no custom template, I want to pull the default. If a user decides to customize the template it should be saved in a customtemplates table - as opposed to the globaltempaltes table. the custom table has all the globaltemplates fields plus a userid and an id relating to which global it is replacing.

To flesh this out a bit more, lets say there are 3 templates, and a user wants to customize template 2 only. I would normaly pull the whole globaltemplates table and whatever relates to the user in the customtemplates table. Then, in the class property I'd do something in the get like this:

MyTemplateA
get { return customtemplates.A ?? globaltemplates.A; }

Can I do this using straight ef4/linq without poco? Would a partial class with some additional properties like the get above work?

Since i'm always editing only the customtemplates table (add/edit/delete) it doesn't matter which version of the template I pull. I guess it could get hairy figuring out if it's an insert or an update.

Upvotes: 1

Views: 97

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

In my opinion it will not work as you expect because EF closely relates entity to table. You cannot have single entity mapped to two tables except very special situations like splitting or inheritance.

So if you have Template entity it can be mapped only to single table but you have two. What you can do is to use TPC inheritance where Template will be a base entity mapped to GlobalTemplates table and UserTemplate will be derived entity mapped to UserTemplates table. TPC (table per concrete type) is type of inheritance where table for derived entity contains all columns from table for parent entity.

But inheritance still has a few problems for your scenario:

  • Template is editable - if you want to have it read only you must correctly handle it in your application logic. Any changes to attached Template instance will be saved when you call SaveChanges on the context.
  • When you load Template you cannot directly convert it to UserTemplate to make it user specific. You must create new instance of UserTemplate and copy properties from Template to the newly created instance.

Upvotes: 1

Related Questions