Retrieve data from DbContext with strings

c# entity-framework entity-framework-core

Question

With Entity Framework you can easily get data from the database doing something like this:

var allBooks = BookContext.Books;

So this code returns all books from the "Book" table.

But I'm getting a string back that tells me from what "table" I need the data from. So I have something like this:

public void GetData(string entity) // entity = "Book"
{
    // Get data using the "entity" string from BookContext
    BookContext.FromString(entity); // for exmaple
}

Is there a way to retrieve data from the BookContext using a string?

Accepted Answer

A quick look to the source code of EF7 reveals that, in contrast to the previous versions, there isn't any Set(Type entityType) method in the DbContext class. There is only the it's generic version Set<TEntity>().

So I think, it isn't possible without using some obscure reflection. (Obscure because EF7 doesn't have any non-generic version of the DbSet class which makes working with the set obtained by the reflection quite difficult)



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why