How to transform string to entity object?

c# entity-framework-6


I need to dynamically get an entity object value from string. something like this :

string s = "UserMaster";
string param = "MyUser";
object o = database.s.Find(param);
//I need o to become like object o = db.UserMaster.Find(MyUser);

Sorry I don't know the name if there's already a function to do this. Thank you for your guidance :)

Edited : Ok so here is the bigger picture :

string myString = "Hi my name is [UserMaster.Name] and my school is [SchoolMaster.SchoolName]";

Let's say I got string "[UserMaster.Name]" & "[SchoolMaster.SchoolName]", UserMaster and SchoolMaster is an entity name. UserMaster has 'Name' property and SchoolMaster has 'SchoolName' property. I need to transform "[UserMaster.Name]" to its value, let's say "MyName" and "SchoolMaster.SchoolName" to "MySchoolName".

9/25/2019 9:59:02 AM

Popular Answer

You can use Expression to dynamically create code:

static object DynamicallyGet(string name, params object[] key) {

    var entityName = Expression.Parameter(typeof(string), "entityName");
    var keyValue = Expression.Parameter(typeof(object[]), "keyValue");
    var db = Expression.Variable(typeof(RainDB), "database");
    IList<Expression> procedures = new List<Expression>();

    procedures.Add(Expression.Assign(db, Expression.New(typeof(RainDB))));

    var entityType = typeof(RainDB).GetProperty(name);
    var callMethod = Expression.Call(Expression.MakeMemberAccess(db, entityType), entityType.PropertyType.GetMethod("Find"), keyValue);


    var body = Expression.Block(new[] { db }, procedures);
    var lambda = Expression.Lambda<Func<string, object[], object>>(body, entityName, keyValue).Compile();

    return lambda(name , key);

//Call Function:

9/25/2019 10:58:41 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow