简体   繁体   中英

Return Linq result to a dataset - GetCommand Is Not a Property

I'm trying the first solution mentioned in - http://forums.asp.net/t/1320587.aspx , to return the linq result to a dataset. But I dont get the 'GetCommand' property after 'mdb'. The error says MedianEntities does not contain a definition for 'GetCommand'. Are you missing an assembly.

What else should I include to fix this.

public DataSet GetAllRecords()
  {
    DataSet ds = new DataSet();
    MEDIANEntities mdb = new MEDIANEntities();
    var query = (from j in mdb.tblCountries 
                 orderby j.CountryName ascending select j);
    SqlCommand cmd = (SqlCommand)mdb.GetCommand(query);     //error here
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(ds);
    return ds;
  }

Using .Netframework 4.0 and Entity Model

DataContext and GetCommand is for LINQ-To-SQL, you want to work with LINQ-To-Entity.

There are multiple issues, your entities MEDIANEntities could be DbContext, the GetCommand is on DataContext class.

Another issue is that your "query" is not an IQueryable, need to remove your .AsEnumerable() from your query.

You can use CopyToDataTable<DataRow>() on your query instead to accomplish what you need. http://msdn.microsoft.com/en-us/library/bb396189.aspx

Another option, which should work but might be hacky, as you are mixing DataContext (linq-to-sql) with (linq-to-entity). Something like that:

                    using (DataContext ctx = new DataContext(mdb.Database.Connection))
                    {
                        DataSet ds = new DataSet();
                        var query = (from j in mdb.tblCountries 
                                     orderby j.CountryName ascending
                                     select j);
                        SqlCommand cmd = (SqlCommand)ctx.GetCommand(query);
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        da.Fill(ds);
                        return ds;
                    }

More info on GetCommand:

DataContext.GetCommand

Namespace: System.Data.Linq

Assembly: System.Data.Linq (in System.Data.Linq.dll)

http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.getcommand.aspx

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