locked
Create Entity Framework proxy instances with reflection RRS feed

  • Question

  • Hello Guys,

       I started to use EF5 recently to migrate some projects, and, generating the model from the database, i noticed that it uses entity proxies by default in this version of EF.

       I need in some point of the code, create instances of classes by reflection only knowing the string with the type (example: "Person", "Car").

       How can i create a bunch of proxy instances with only the strings of the class names?

    thanks!


    • Edited by Jorge_M_P Thursday, March 21, 2013 4:41 PM
    Thursday, March 21, 2013 2:38 PM

Answers

  • Thanks for the reply,

    I only had time to answer now,

    I have found  a solution that suits for my case:

    var method = myObjectContext().GetType().GetMethod("CreateObject");
    method = method.MakeGenericMethod(Type.GetType("MYPROJECT.MYCLASS"));
    var entity = method.Invoke(myObjectContext(), null);
    return entity;
    

    Thanks!

    • Proposed as answer by JA Reyes Friday, March 22, 2013 3:52 PM
    • Marked as answer by Jorge_M_P Friday, March 22, 2013 4:15 PM
    Friday, March 22, 2013 3:49 PM

All replies

  • Hi Jorge_M_P,

    Welcome to the MSDN forum.

    Could you please let me know whether or not the DbContext class is provided? If you know the types of entities you want to create and DbContext class, it will be easy to achieve: context.Set<T>().Create()

    Good day.


    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, March 22, 2013 7:45 AM
  • Thanks for the reply,

    I only had time to answer now,

    I have found  a solution that suits for my case:

    var method = myObjectContext().GetType().GetMethod("CreateObject");
    method = method.MakeGenericMethod(Type.GetType("MYPROJECT.MYCLASS"));
    var entity = method.Invoke(myObjectContext(), null);
    return entity;
    

    Thanks!

    • Proposed as answer by JA Reyes Friday, March 22, 2013 3:52 PM
    • Marked as answer by Jorge_M_P Friday, March 22, 2013 4:15 PM
    Friday, March 22, 2013 3:49 PM