转一个ef用到的方法,sql转DbRawSqlQuery,其实它会比普通sql查询多执行一次查询,可以理解为为了得到一个类型表头

其实它比普通sql查询多执行一次查询,可以理解为为了得到一个类型表头

所以,你得到的查询结果时,它把sql执行了两遍,不过应该是必须的吧,可能因为DbRawSqlQuery需要一个类型表头以匹配数据体,

而有时,我们查询的sql是多表的,不单是一个模型的类型,这里就会建立一个匿名的类型表头,

比如:Int32,String,Long,DateTime ,的类型表头,用于对应四个对应数值类型字段的,数据表体,

有时这也是必须的,但这有点效率问题,需要的人可以注意一下

public static System.Data.Entity.Infrastructure.DbRawSqlQuery DynamicSqlQueryMethod(Database database, string sql, params object[] parameters) {
            TypeBuilder builder = CreateTypeBuilder(
                    "MyDynamicAssembly", "MyDynamicModule", "MyDynamicType");

            Exception ex0 = null;
            using (System.Data.IDbCommand command = database.Connection.CreateCommand()) {
                try {
                    database.Connection.Open();
                    command.CommandText = sql;
                    command.CommandTimeout = command.Connection.ConnectionTimeout;
                    if (parameters != null)
                        foreach (var param in parameters) {
                            command.Parameters.Add(param);
                        }

                    using (System.Data.IDataReader reader = command.ExecuteReader()) {
                        var schema = reader.GetSchemaTable();

                        foreach (System.Data.DataRow row in schema.Rows) {
                            string name = (string)row["ColumnName"];
                            Type type = (Type)row["DataType"];
                            if (type != typeof(string) && (bool)row.ItemArray[schema.Columns.IndexOf("AllowDbNull")]) {
                                type = typeof(Nullable<>).MakeGenericType(type);
                            }
                            CreateAutoImplementedProperty(builder, name, type);
                        }
                    }
                }
                catch (Exception ex) {
                    Logger.Info("select sql fail. " + ex.Message);
                    ex0 = ex;
                }
                finally {
                    //database.Connection.Close();
                    command.Parameters.Clear();
                }
            }
            if (ex0 != null) throw ex0;

            Type resultType = builder.CreateType();
            return database.SqlQuery(resultType, sql);
        }

  

posted @ 2017-09-09 14:48  以函  阅读(358)  评论(0编辑  收藏  举报