6

I have a DbContext class and I'm using code first apporach in my application. I have few common standard tables that contains "Id" and "Value" columns and i want to query them passing the table name and column name but there is no option in entity framework to pass.

Example:

Common tables:

Client_ClientDepartment (Id, Value) 
Client_ClientDesignation (Id, Value)
Client_ClientCompany (Id, Value)

What I want to do is to pass table name and Id to get the value. I have created a common method as

    public string GetClientValue(string id, string tableName)
    {
        DatabaseContext dbContext = new DatabaseContext();
        //Query the database and get value based on table and id.
        string value = dbContent. ("query here")             
        return value ;
    }

Can I do it in entity framework? Is it possible?

0

3 Answers 3

2
using ( DatabaseContext dbContext = new DatabaseContext()) 
{ 
    var blogs = dbContext.Database.SqlQuery<>("query here").ToList(); 
}
0
1

I believe you can run a custom query like this

using (var context = new BloggingContext()) 
{ 
    var blogNames = context.Database.SqlQuery<string>( 
                       "SELECT Name FROM dbo.Blogs").ToList(); 
}

Source: https://msdn.microsoft.com/en-us/library/jj592907(v=vs.113).aspx

Sorry I had to answer instead of comment, but don't got the badge yet.

-1

Actually, you normally don't pass table and column names in EF. You have classes and properties, which become tables and columns in the resulting database. Your context should look something like this:

public class DatabaseContext : DbContext
{
    public DatabaseContext(): base(YourWebConfigConnectionStringName){}
    public DbSet<Client_ClientDepartment> ClientDepartment { get; set; }
    public DbSet<Client_ClientDesignation> ClientDesignation { get; set; }

With this you are basically registering your "table" classes.

You then address them in code like this:

using (var context=new DatabaseContext())
{
    var department = context.ClientDepartment.First(d => d.Id == someIdVariable);

Which is the analogy to a SQL query SELECT TOP 1 department WHERE ID=someId

You can also pass SQL statements as described in the other answers, but that too will only work if you properly registered your classes as DBSets in your DatabaseContext class.

P.S: I left out the Database initializer in the DBContext class, which is something you also need in code first.

1
  • The main reason I'm asking this question is to make a generic function to get value from a table passing the table name and column (primary key). I'm trying to perform it using entity framework but i guess it has to be an inline query :( Thanks for the information btw. Commented Jan 27, 2017 at 11:55

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.