.NET 查看 EF 查詢生成的SQL 語句

添加 引用:
using System.Data.Objects;

var results = db.tb_product.Where(s => s.ID == 2160);
var sql = (results as ObjectQuery<tb_product>).ToTraceString();


另一種方法:
using (var context = new TestDBEntities())
{
    var query = from p in context.Parents
                where p.Name == "Lingzhi"
                select p;

    ObjectQuery<Parent> parents = query as ObjectQuery<Parent>;
    if (parents != null)
    {
        string sql = parents.ToTraceString();
    }
}

在EF4.1中,可以直接 使用 ToString() 
using (var context = new MyDbContext())
{
    var people = from p in context.People
                 where p.PersonID > 100
                 select p;

    string sql = people.ToString();
}

大 家應該已經猜到,這裏的ToString()方法其實也就是調用了ObjectQuery<>的ToTraceString()方法。 DbQuery<>.ToString() ==> System.Data.Entity.Internal.Linq.InternalQuery<>.ToString()方法,此方法 在.NET Reflector得到的實現是這樣的:

public override string ToString()
{
    
return this._objectQuery.ToTraceString();
}



查ef生成sql的例子

  [TestFixture]

    public class TestEFModel

    {

        [Test]

        public void Select()

        {

            using (var edm = new NorthwindEntities())

            {

                //基於表達式的查詢語法

                ObjectQuery<Customers> customers = edm.Customers;

                IQueryable<Customers> cust1 = from c in customers

                                              select c;

                Assert.Greater(cust1.Count(), 0);

                //使用ObjectQuery類的ToTraceString()方法顯示查詢SQL語句

                Console.WriteLine(customers.ToTraceString());

 

 

            }

        }

    }

}

輸出:

SELECT

[Extent1].[CustomerID] AS [CustomerID],

[Extent1].[CompanyName] AS [CompanyName],

[Extent1].[ContactName] AS [ContactName],

[Extent1].[ContactTitle] AS [ContactTitle],

[Extent1].[Address] AS [Address],

[Extent1].[City] AS [City],

[Extent1].[Region] AS [Region],

[Extent1].[PostalCode] AS [PostalCode],

[Extent1].[Country] AS [Country],

[Extent1].[Phone] AS [Phone],

[Extent1].[Fax] AS [Fax]

FROM [dbo].[Customers] AS [Extent1]


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章