由于我的数据库中有一部分表是动态生成的,因此没有为它生成实体类,在实际应用中是根据记录到表中的信息动态地生成create table, insert, update, delete, select 语句的但是现在发现无法使用 EF 中得到的连接创建 DbCommand 进行普通的查询
using (DAL.PrintsysEntities db = new DAL.PrintsysEntities()) {
System.Data.Common.DbConnection conn = db.Connection;
using (System.Data.Common.DbCommand cmd = conn.CreateCommand()) { cmd.CommandText = "select now()"; if (conn.State != ConnectionState.Open)
conn.Open();
using (System.Data.Common.DbDataReader reader = cmd.ExecuteReader()) {
if (reader.Read()) {
object now = reader.GetDateTime(0);
}
}
}
}db.Connection 返回的是 System.Data.EntityClient.EntityConnection 类型 
用它得到的 Command 是 System.Data.EntityClient.EntityCommand 类型
用它们无法执行普通的 sql 语句这个情况应该怎么办?

解决方案 »

  1.   

    context.Database.SqlQuery<string>("select now()")http://mhenrikson.blogspot.in/2011/06/execute-sql-with-entity-framework-4.html
      

  2.   

    EntityCommand 是对应的数据库 Command 的代理,可直接运行sql代码,只是参数名称不能包含特殊符号(如@),因它会自动转换。
      

  3.   

    http://www.cnblogs.com/wintersun/archive/2010/12/12/1903861.html
      

  4.   


    db 有 Database 这个属性,但是字是 string 类型,没有 ExecuteSqlCommand 这个方法啊
      

  5.   


    context.Database 是 string 类型,没有 SqlQuery 这个方法啊
      

  6.   

    void Main() 

     
      var constr = @"Data Source=.;Initial Catalog=Northwind;Integrated Security=True"; 
      var context = new DataContext(constr) ; 
       
     string[] ss=context.ExecuteQuery<string>("select now()").ToArray(); 
     foreach(string s in ss) 
     { 
       Console.WriteLine(s); 
     } 
       
                   
      

  7.   

    因为EF无法使用sql语句,建议你建视图获取对象和数据.不知道你的数据有没有什么特殊的?是否考虑过把动态表转换成实体表.?
      

  8.   


    版主,我用的是 MySQL,不是SQL Server
    另外,这种查询要求指定返回类型,如果我查的不是当前时间,而是一个表,并且这个表是在运行时动态创建的,我就无法指定返回类型了。
      

  9.   

    好象此题无解了,只能用 MySQL Ado.net