I'm using entity framework, and I need to get a list of entities only by passing the name of the entity.
Example:
string tableName = "PRODUCT";
List<tableName> myList = (from prod in dbContext.tableName
select prod).ToList();
What I can't get to do, is that, using the table name (string) to make a EF query (or LINQ).
I'm trying to get this to work by using Reflection or EntityDataModel, but I just can't.
Have you tried something like this (source):
var table = context.ExecuteStoreQuery<ResultTableTemplate>("SELECT ... FROM " + tableName);
Related
In ASP.NET Core 5 MVC, I have:
dbContext = mfdDbContext
var myquery = select * from teachers order by id desc
The normal convention is this:
var results = mfdDbContext.SomeModel
.FromSqlRaw("select id, firstName, lastName from teachers order by id desc")
.ToList();
But I don't have a model class.
How do I implement the above raw query without a model? Then generate my own model.
Thanks
You cannot achieve this with EF. You have to have model class anyway. That's why EF is so powerful.
Instead, you could use Dapper
https://dapper-tutorial.net/query
string sql = "select * from teachers order by id desc";
using (var connection = new SqlConnection(connectionString))
{
var data = connection.Query(sql).ToList();
// use data
}
but anyway, you have manually to get the columns. I would recommend to have a DB Model registered with EF, it will make your life easier.
I want query all the existing tables whose name begin with specific string in database using oledb GetSchema method.
In other words I am looking for equivalent of the following sql query:
SELECT * FROM information_schema.tables WHERE table_name LIKE 'customer%'
Something like:
String[] tableRestrictions = new String[4];
tableRestrictions[2] = "%customer";
DataTable customerTables = conn.GetSchema("Tables", tableRestrictions );
In this case the table name I want to query from is Dynamic. Therefore I needed to get the whole table name first.
It seems there is not efficient way to do that but using an iteration.
I came to this conclusion that using Linq provides the neatest solution(Thanks to Tim's answer to a similar case):
// Get the tables using GetSchema:
dtbTables = dbConnection.GetSchema("tables");
// use linq to get the table whose name matches the criteria:
DataRow recSpecificTable = dbConnection.GetSchema("Tables").AsEnumerable()
.Where(r => r.Field<string>("TABLE_NAME")
.StartsWith("customer")).FirstOrDefault();
// Now the table name I am looking for:
tableName = Convert.ToString(recSpecificTable["TABLE_NAME"]).Trim();
I want to use this query
select datename (dw, CURRENT_TIMESTAMP)AS DAY ;
to get week day name and use it to insert record to table.
how can I use this query by entity framework
I use this method but it doesn't work:
private void GetDayName(DateTime ReportDate,out string DayName)
{
using (var context = new Daily_ReportEntities3())
{
var day_name= context.ExecuteStoreQuery ("select datename (dw,'|| + ReportDate + ||') as NameOfDay", null).ToList();
DayName = day_name=.ToString();
}
}
You cannot execute transact SQL statements from Entity Framework directly.
But you can Execute Functions from within ObjectContext.
First define a scalar value function returning data you need and next import it to your Store model. You'll be able to execute it via ObjectContext.ExecuteFunction method.
PS. Consider implementing your functionality using System.Globalization.Calendar object, that can supply the information about day names based on certain culture.
Should be like this:
var day_name = context.Database.SqlQuery<string>
("select datename (dw,'|| + ReportDate + ||') as NameOfDay").FirstOrDefault<string>();
see
http://msdn.microsoft.com/en-us/library/gg696545%28v=vs.103%29.aspx
I'm creating some manual SQL updates using C#, Entity Framework 4 and DB2, in the way of this naive example...
var UpdateCommand = "UPDATE MY_SCHEMA." + this.Entities.PRODUCT.EntitySet.Name +
" SET STOCK=0";
var AffectedRows = this.Entities.ExeceuteStoreCommand(UpdateCommand);
I want to specify the schema as with the entity name (which later, if implememented in a reusable library method, could be passed as parameter). So, I tried...
var Container = this.Entities.MetadataWorkspace.GetEntityContainer(this.Entities.DefaultContainerName, System.Data.Metadata.Edm.DataSpace.CSpace);
var Set = Container.GetEntitySetByName(this.Entities.PRODUCT.EntitySet.Name, true);
var SchemaName = Set.MetadataProperties["Schema"].Value;
The problem is that the SchemaName returned is always null!
I've seen solutions based on parsing SQL generated by Entity Framework, but that could be fooled (text can containg anything), or SQL-Server specific. The idea is to be as DB agnostic as EF is.
Question is... how to get an entity schema name from EF objects, not parsing generated SQL and being db-agnostic?
you can get it from SSpace.
In ef5 following works. Probably will work in ef4 also
// for code-first
var Container = this.Entities.MetadataWorkspace.GetEntityContainer("CodeFirstDatabase", DataSpace.SSpace);
// db-first
var Container = this.Entities.MetadataWorkspace.GetEntityContainer("DbFirstModelStoreContainer", DataSpace.SSpace);
var schemaName = Container.GetEntitySetByName(this.Entities.PRODUCT.EntitySet.Name, true).Schema
// or
var set = Container.GetEntitySetByName(this.Entities.PRODUCT.EntitySet.Name, true);
var schemaName = Set.MetadataProperties["Schema"].Value;
Up to now (with NHibernate) I've used entity mapping and not really got involved with creating raw sql queries - but somethings come up where I need to do exactly that.
The problem I have is I want to automatically map the columns aliases of my query to a Dto object.
This works, but i have to specify the column alias' in the order of the query.
SQL
string sql = "select mycol1 as ColumnOne from mytable";
NHibernate Query
var query = session.CreateSQLQuery(sql)
.AddScalar("ColumnOne", NHibernateUtil.Int32)
.SetResultTransformer(
NHibernate.Transform.Transformers.AliasToBean<MyDtoObject>()
);
MyDtoObject
public class MyDtoObject
{
public int ColumnOne {get;set;}
}
But is there a way to making NHibernate automate the mapping between the columns in the query and the Dto without creating a mapping class?
I've seen some examples of using aliases in the query e.g.
string sql = "select mycol1 as {ColumnOne} as ColumnOne from mytable"; /// ???
But cannot get this to work as the alias {ColumnOne} appear not to be replaced before being sent to the db as a sql statement.
Any idea?
TIA
Sam
Maybe System.Linq.Dymanic will help:
use System.Linq.Dynamic;
string ColumnAlisName = "ColumnOne";
var query = mytable.Select(String.Format("new (mycol1 as {0})",ColumnAlisName));