1

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".

Nico Yang
  • 13
  • 4
  • The Find() method Find object by its primary key, so if param is key, you can use it – Phat Huynh Sep 25 '19 at 09:36
  • This sounds like an XY problem to me. Let's say you get this working and you have your object `o` that contains whatever type is specified by `s`, how would you intend to use that? – DavidG Sep 25 '19 at 09:39
  • the problem is the DataEntity does not contain a definition for 's' since 's' is string and not an entity object. – Nico Yang Sep 25 '19 at 09:41
  • 1
    How would that be useful? Give us the big picture what are you trying to do with passing string values around? – Mat J Sep 25 '19 at 09:42
  • @DavidG I will use it as a normal entity object of course. So if 'UserMaster' has Name property, I could use it like : o.Name – Nico Yang Sep 25 '19 at 09:42
  • Well, you can't do `o.Name` because `o` is an `object`. Do you see my point yet? – DavidG Sep 25 '19 at 09:43
  • 1
    Possible duplicate of [Entity framework - get entity by name](https://stackoverflow.com/questions/12455389/entity-framework-get-entity-by-name) – Gabriel Llorico Sep 25 '19 at 09:53

2 Answers2

0

Dynamically, when you have the DbSet as string (your case):

DbSet mySet = context.Set(Type.GetType("<Your Entity Name>"));

Source: https://entityframeworkcore.com/knowledge-base/33940507/find-a-generic-dbset-in-a-dbcontext-dynamically

Besides all that, building dynamically a string that has parameters inside is common practice.

It is usually achieved by using curly brackets inside the string, e.g.:

this is in a database column: "Hello, my name is {User.FirstName}, I come from {User.Country}"

These are usually predefined values and in code you can replace them because you expect them.

Then you do:

var userId = ...get this from session or from whatever you have in your context.
var dbUser = db.User.FirstOrDefault(x => x.UserId == userId);

var template = db.Templates.FirstOrDefault(x => x.TemplateName = "userTemplate");

// template is the Db table and TemplateValue is the column
var text = template.TemplateValue;

text = text.Replace("{User.FirstName}", dbUser.Firstname);
text = text.Replace("{User.Country}", dbUser.Country);

That works, but you have to know beforehand the parameters (they should be predefined). If you have no idea what parameter should be sent (at least the sender should know that these exist as DB tables/columns), then yeah, it's more tricky and you should go with the dynamic approach that we suggested.

Good luck!

st_stefanov
  • 1,147
  • 1
  • 10
  • 28
0

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);

    procedures.Add(callMethod);

    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:

DynamicallyGet("UserMaster","MyUser")
包俊仁
  • 42
  • 5