0

I am trying to do some dynamic code using Entity Framework. I have a model (Model1) with one table(Test1), it's simple. What I'm trying to do is accessing the model Test1 programatically with the name of the table, to use it after in differents tasks. I was looking for in google and I have found Finding entities by key in entity framework but it's doesnt work, or I don't have any idea...

When I ran this code it breaks on trying to set entityProperty

Model1Container m = new Model1Container();
            PropertyInfo entityProperty = m.GetType().GetProperties().Where(t => t.Name == "Test1").Single();
            var baseQuery = (IQueryable<IIdentity>)entityProperty.GetValue(m, null);

Sorry for the explanation.

Any ideas?

kartGIS
  • 464
  • 5
  • 9

1 Answers1

0

You create an object with a string name and set its properties:

public class Test
{
    //All my classes have these properties
    //You can set up an interface and in the method you can set entity to an interface type
    //You can even put these interfaces on edmx generated entities
    //http://stackoverflow.com/questions/14059455/adding-validation-attributes-with-an-entity-framework-data-model
    public string AString { get; set; }
    public DateTime ADate { get; set; }
}

public class HomeController : Controller
{
    public ActionResult IndexStackOverflow101()
    {
        Assembly assembly = Assembly.Load("Testy20161006");
        Type t = assembly.GetType("Testy20161006.Controllers." + "Test");
        Object entity = (Object)Activator.CreateInstance(t);
        PropertyInfo entityProperty = t.GetProperty("AString");
        PropertyInfo entityPropertyTwo = t.GetProperty("ADate");
        entityProperty.SetValue(entity, Convert.ChangeType("ap", entityProperty.PropertyType), null);
        entityPropertyTwo.SetValue(entity, Convert.ChangeType(DateTime.Now, entityPropertyTwo.PropertyType), null);
kblau
  • 1,886
  • 1
  • 6
  • 16
  • I think I explained wrong.. What I want is to obtain programatically the instance of one entity, that I have in the model. This way, I can use a string to obtain entity without to write m.Test1...., instead of I want something similar to m["Test1"] (not that way but similar). Thx – kartGIS Jul 18 '17 at 06:20
  • You can create partial classes of your entities and even put [required] or other attributes on fields through metadata: http://stackoverflow.com/questions/14059455/adding-validation-attributes-with-an-entity-framework-data-model Once you do that you can make each entity derive from IEntity and define IEntity. You can then do Assembly assembly = Assembly.Load("Testy20161006"); Type t = assembly.GetType("Testy20161006.Controllers." + "Test"); IEntity entity = (Object)Activator.CreateInstance(t); credit John Skeet – kblau Jul 18 '17 at 18:07
  • Thx @kblau! I did it that way – kartGIS Jul 20 '17 at 23:37