jordanpg
jordanpg

Reputation: 6516

Can the code-first features of EF 4.1 and greater be used when the DB schema is unknown until runtime?

This does not seem to be explicitly listed as a feature in any of the sparse examples I can find, for example:

http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-1-introduction-and-model.aspx

http://www.codeproject.com/Articles/336187/code-first-practical-case

or

http://blogs.msdn.com/b/adonet/archive/2011/09/28/ef-4-2-code-first-walkthrough.aspx

But I think the DbContext docs at least imply that it's possible: http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.103).aspx

DbContext is usually used with a derived type that contains DbSet properties for the root entities of the model. These sets are automatically initialized when the instance of the derived class is created.

My goal is to use the EF to access a DB through a WCF data service from a Silverlight client, where the some of the columns are unknown at runtime. Any better ideas would be appreciated

Upvotes: 2

Views: 144

Answers (2)

jordanpg
jordanpg

Reputation: 6516

If anyone is interested, here is a synopsis of how to change the EDMX files to match a DB discovered at runtime:

  1. Get and parse schema from the database (simple XML)
  2. Put the schema in a format that is comparable with the EDMX metadata (more complex XML)
  3. Use a tool like this one: http://efmodeladapter.codeplex.com/ to make the changes to the metadata (some assembly required)
  4. Instantiate the data model

There is a commercial tool to do the same, but it's not free: http://huagati.com/dbmltools/

And here is the best list of other, more palatable options: Modifying an Entity Framework Model at Run-Time

Upvotes: 0

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

Neither WCF or EF is suitable technology for this situation. WCF and its autogenerated proxies expects compile time defined model - you can avoid this but as a result you will not work with strongly typed data contracts but with "generic data" and you will work with them on XML or JSON level.

In case of EF it is even worse there is no easy workaround to get dynamic behavior. You can change DB or even mapping (but not with code first - only with EDMX) in dynamic way but still at the end you need compiled classes representing your mapped data.

The part of documentation you are referencing is not about dynamic creation of mapping but only about dynamic initialization of mapping defined in design time.

Upvotes: 1

Related Questions