Reputation: 1899
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?
Upvotes: 6
Views: 5464
Reputation: 2917
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.
Upvotes: -1
Reputation: 135
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.
Upvotes: 1
Reputation: 244
using ( DatabaseContext dbContext = new DatabaseContext())
{
var blogs = dbContext.Database.SqlQuery<>("query here").ToList();
}
Upvotes: 2