【问题标题】:How to make a query string with entity framework如何使用实体框架制作查询字符串
【发布时间】:2013-04-10 15:48:16
【问题描述】:

我有一个复杂的查询,它可以根据接收到的参数而增长或变小。示例:

public string CreateQuery(string[]  fields)
{
    var query = "SELECT student_name,student_last_name FROM students";

    if(fields[0]!= "")
    {
        query += " WHERE studient_id='"+fields[0]+"'";
    }

    if(fields[1] != null)
    {
        //them....
    }
    //and so on

    return query;
}

所以我需要像 webmatrix 一样执行该查询

ViewBag.StudentInf = db.Query("Query string here...");

那么,如何使用实体框架执行查询字符串?

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    你真的不应该这样做。有人对您执行 SQL 注入攻击的风险很大。

    您可以执行此answer 中推荐的操作。

    但如果你真的想这样做,你可以这样做:

    using (System.Data.Common.DbCommand cmd = db.Database.Connection.CreateCommand())
    {
        cmd.CommandText = "SELECT *...";
    }
    

    【讨论】:

      【解决方案2】:

      对于 .NET Framework 4 及更高版本:使用ObjectContext.ExecuteStoreCommand()

      教程here

      或者试试这个功能

      static void ExecuteSql(ObjectContext c, string sql)
      {
          var entityConnection = (System.Data.EntityClient.EntityConnection)c.Connection;
          DbConnection conn = entityConnection.StoreConnection;    
          ConnectionState initialState = conn.State;
      
          try
          {
              if (initialState != ConnectionState.Open)
                  conn.Open();  
      
              using (DbCommand cmd = conn.CreateCommand())
              {
                  cmd.CommandText = sql;
                  cmd.ExecuteNonQuery();
              }
          }
          finally
          {
              if (initialState != ConnectionState.Open)
                  conn.Close(); 
          }
      }
      

      【讨论】:

        【解决方案3】:

        如果您的问题是关于使用 Linq to Entities 构建动态查询,您至少可以使用 Dynamic Linq

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-28
          • 1970-01-01
          • 1970-01-01
          • 2013-06-30
          • 1970-01-01
          相关资源
          最近更新 更多