开发者

Dynamically loading SQL tables in Entity Framework

I need to dynamically access some SQL tables hopefully using the Entity Framework. Here's some pseudo code:

var Account = DB.Accounts.SingleOrDefault(x => x.ID == 12345);

which will return me an Account object and this contains some fields called "PREFIX", "CAMPAIGN ID" and further information about the accounts are stored in separate SQL tables with the naming convention of PREFIX_CAMPAIGNID_MAIN.

The tables all have the same fi开发者_如何学JAVAelds so I was thinking of creating a new Entity that isn't mapped anywhere and then dynamically loading it, like so:

var STA01_MAIN = new MyAccount(); // my "un-mapped" entity

DB.LoadTable('STA01_MAIN').LoadInto(STA01_MAIN);

I can now get anything about the STA01_MAIN account: STA01_MAIN.AccountId.

So my question is: how do I access these tables using the Entity Framework?


I don't think EF has a LoadTable and LoadInto method, but ObjectOntext.ExecuteStoreQuery might be what you're looking for:

http://msdn.microsoft.com/en-us/library/dd487208.aspx

This should let you execute an arbitrary query against your database, and then map the results to an arbitrary type that you specify (even if it's not otherwise mapped in EF).

It goes without saying that you would be responsible for putting together a query that supplied the necessary columns for mapping into the destination type, and also adjusting said query when this type changes.

Here's some further discussion concerning its usage

http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/44cf5582-63f8-4f81-8029-7b43469c028d/

Have you considered mapping all of these tables (with the identical columns) into an inheritance relationship in EF, and then querying them as

db.BaseTypes.OfType<SpecificType>().Where(/*.....*/);

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜