Cast a property to its actual type dynamically using reflection

后端 未结 7 992
梦毁少年i
梦毁少年i 2020-12-09 08:29

I need to cast a property to its actual type dynamically. How do I/Can I do this using reflection?

To explain the real scenario that I am working on a bit. I am tryi

7条回答
  •  天涯浪人
    2020-12-09 08:53

    Though I should post the solution to the real world problem.

    string objectType = "MyProperty";
    
    using (MyEntitiesContext entitiesContext = new MyEntitiesContext())
    {
    try
    {
        string queryString = @"SELECT VALUE " + objectType+  " FROM MyEntitiesContext." + objectType + " AS " + objectType + " WHERE " + objectType + ".id = @id";
    
        IQueryable query = entitiesContext.CreateQuery(queryString, new ObjectParameter("id", objectId));
    
        foreach (Object result in query)
        {
            return result;
        }
    }
    catch (EntitySqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    }
    
    return null;
    
    
    

    I think the new CLR4 dynamic keywork might be the "nice" solution.

    Thanks for all the responces.

    提交回复
    热议问题