Tuesday, 15 May 2012

.net - Extract model information from Entity Framework 4.3 - 5 -



.net - Extract model information from Entity Framework 4.3 - 5 -

i want implement several extensions entity framework. allow met take 1 example.

void insertorupdate<t, tupdatefields, tinsertfields, tkey>( dbcontext context, ienumerable<t> data, expression<func<t, tupdatefields>> updatefields, expression<func<t, tinsertfields>> insertfields, expression<func<t, tkey>> key)

and supposed used this.

var dc = new somecontext(); var user = new user() { /* initialize */ }; var array = new[] { user }; dc.insertorupdate( array, x => new { x.username, x.password, x.lastloggedin }, x => new { x.username, x.password, x.email, x.dateadded, x.lastloggedin }, x => x.username);

the method generate sql string , pass dbcontext.database.executesqlcommand method. in order generate sql need extract table , field names model information, in case different class , property names.

(for illustration username property corresponds user_name field in db)

i know can set in entity info annotations, defined in modelbuilder straight in onmodelcreating(dbmodelbuilder) method of dbcontext or defined in form of entitytypeconfiguration<t> implementation , passed model builder configuration in same method.

how can retrieve tables' , fields' names dbcontext instance? possible @ all?

i appears easy. if next class definition

[table("user")] public class user { [column("user_id")] public int32 userid {get;set;} [column("user_name")] public string username {get;set;} [column("email")] public string email {get;set;} [column("join_date")] public datetime dateadded {get;set;} [column("password")] public string password {get;set;} [column("last_logged_in")] public datetime lastloggedin {get;set;} }

i utilize next technique

void insertorupdate<t, tupdatefields, tinsertfields, tkey>( dbcontext context, ienumerable<t> data, expression<func<t, tupdatefields>> updatefields, expression<func<t, tinsertfields>> insertfields, expression<func<t, tkey>> key){ var sql = context.set<t>().select(updatefields).tostring(); // stuff }

eventually sql variable contain this

select 1 [c1], [extent1].[user_name] [user_name], [extent1].[password] [password], [extent1].[last_logged_in] [last_logged_in] [dbo].[tbuser] [extent1]

this statement can parsed find out table , column names. columns in produced sql appears in same order indicated in anonymous type

.net entity-framework-5 entity-framework-4.3

No comments:

Post a Comment