4

Let's say that I have

DBContext principal = new DBContext();
var x = principal.GetType().GetProperty("SomeClass").GetType();

I now have the PropertyInfo of DbSet< SomeClass >

What I'm trying to do now is somehow iterate (convert to list for example) and get the values from each row in the table.

imagine I could do this:

x[0] // would be the 0th entery in DbSet<SomeClass>, the first row aka of type SomeClass

From here I would know how to further drill down and access properties (using the same principle as above)

6
  • 2
    This sounds like an XY problem. Why are you using reflection instead of generics, like the DbContext.Set<T>() method? Commented May 9, 2017 at 21:26
  • Because I'm trying to create my own custom ValidationAttribute and in the constructor I'm sending Type class as a parameter. If it was a function I'd use generics but I cant write something like public Constructor<T> Commented May 9, 2017 at 21:28
  • 2
    Use DBContext.Set<T>? It's been a while since I've used EF but I'm pretty sure there was a generic way that accepts a type. Commented May 9, 2017 at 21:30
  • Are you sure you want to access the database from within an attribute? Commented May 9, 2017 at 21:30
  • var myName = principal.set<MyClass>().ToList()[0].FirstName; ConsoleWriteline(x); should work in theory then but I get stuck in an infinite loop for some reasons @JeroenVannevel Commented May 9, 2017 at 21:39

1 Answer 1

6

DbSet implements both IEnumerable and IEnumerable<T>, so something like:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace efAW
{
    class Program
    {

        static IEnumerable GetAllMembers(DbContext db, string dbSetName)
        {
            var pi = db.GetType().GetProperty(dbSetName);
            return (IEnumerable)pi.GetValue(db);
        }
        static void Main(string[] args)
        {
            using (var db = new aw())
            {
                var customers = GetAllMembers(db, "Customers").OfType<Customer>().ToList();
            }
        }
    }
}

David

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.