Ley
Ley

Reputation: 41

How to use sql statement in entity framework to return the list of record

I have the the database like in the picture and the code below:

Int32 row_count = ctx.Database.SqlQuery<Int32>("select count(*) from Categories").FirstOrDefault<Int32>() ;

I want to write the code that is the same or similar to the code below:

private void FillDataToList(string Prefix)
    {
    BindingSource bs = new BindingSource();
    using (var ctx=new CambbusPOSEntities()){
      foreach(obj in ctx.SQLManager.Where(a=>a.Entity==Prefix)){
        var query = ctx.Database.SqlQuery<List>(obj.SQL).ToList();
        bs.DataSource = query;
      }
}

}

But it show the error:

Using the generic type 'System.collections.Generic.List' requires 1 type arguments

So do we have another way that use with sql statement in entity?Because I want to store all sql statement in database. Thank you

Upvotes: 0

Views: 3312

Answers (2)

Hans Kesting
Hans Kesting

Reputation: 39274

You apparently want a generic way to get results from a sql query that you specify at runtime. Entity Framework wants to use specific types (known at compile time) that you cannot provide in this way. Also you are ignoring the "query build" features of EF using LINQ. So why use EF?

Maybe you could use an "oldfashioned" DataSet. Then you can fill a generic data structure with the results of any query you provide at runtime.

See for instance Populating a DataSet from a DataAdapter.

Upvotes: 0

Linh Tuan
Linh Tuan

Reputation: 448

You should create one Table model to contain all Property of that Table. Example:

var query = ctx.Database.SqlQuery<Categories>("select * from Categories").ToList();

Upvotes: 1

Related Questions