EF 4.1 Code First Multiple Result Sets

五迷三道 提交于 2019-12-19 07:17:11

问题


I need to execute a Raw SQL query that returns multiple result sets. Is that possible in EF CF ?

Thanks!


回答1:


Description

Yes you can! ;) You can perform a raw sql query using DbCommand in Entity Framework Code First too.

You can perform queries with multiple result sets and jump to the next result set using NextResult() method of the SqlDataReader class.

Sample

namespace MyNamespace
{
    public class MyDbContext : DbContext
    {

    }

    public class Test
    {
        public void Test()
        {
            MyDbContext context = new MyDbContext();

            DbCommand db = context.Database.Connection.CreateCommand();
            db.CommandText = "SELECT propertie1 FROM Table1; SELECT propertie1 from Table2";
            try
            {
                DbDataReader reader = db.ExecuteReader();

                while (reader.Read())
                {
                    // read your data from result set 1
                    string value = Convert.ToString(reader["propertie1"]);
                }

                reader.NextResult();

                while (reader.Read())
                {
                    // read your data from result set 2
                    string value = Convert.ToString(reader["propertie1"]);
                }
            }
            catch
            {
                // Exception handling
            }
            finally
            {
                if (db.Connection.State != ConnectionState.Closed)
                    db.Connection.Close();
            }
        }
    }
}

More Information

  • Using DbContext in EF 4.1 Part 10: Raw SQL Queries


来源:https://stackoverflow.com/questions/8315507/ef-4-1-code-first-multiple-result-sets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!