简体   繁体   中英

Pass table name to dbContext and get values from table in Entity Framework

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?

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM