先说一下查看所生成的SQL的方法,.ToTraceString()
例如:
string entitySQL = "select value a from orders as a;";
参数
var query = db.CreateQuery<Orders>(entitySQL);
Console.WriteLine(query.ToTraceString());
参数可以通过CreateQuery的第二个参数传递进去。
DateTime dt = new DateTime(1997, 1, 1);
ObjectParameter[] ps = { new ObjectParameter("dt", dt) };
ObjectQuery<Orders> query = db.CreateQuery<Orders>("SELECT VALUE Orders FROM Orders WHERE Orders.OrderDate < @dt;", ps);
这里通过@dt将参数传了进去,执行结果:
外键关系
Entity SQL与其它的查询一样,可以通过外键的关系直接取值或判断,如:
ObjectQuery<Orders> query = db.CreateQuery<Orders>(
"SELECT VALUE o FROM Orders AS o WHERE o.Customers.Country = 'Mexico';");
我们直接用o.Customers.Country这是一个一对多的外键关系。
多条件查询
与T-SQL相同,只要用相应的逻辑关键字即可。如:
string entitySQL =
Exists查询
"SELECT VALUE p FROM Products AS p WHERE p.UnitsInStock < p.ReorderLevel and p.UnitsOnOrder = 0;";
ObjectQuery<Products> query = db.CreateQuery<Products>(entitySQL);
做为Where的一个经常用的谓词,Exists的使用方法如下:
string entitySQL = @"SELECT VALUE s FROM Suppliers AS s WHERE
EXISTS(SELECT p FROM s.Products AS p WHERE p.UnitsInStock = 0);";
var query = db.CreateQuery<bool>(entitySQL);
运行后生成的SQL如下:
SELECT
IN查询
[Extent1].[Address] AS [Address],
[Extent1].[City] AS [City],
[Extent1].[CompanyName] AS [CompanyName],
[Extent1].[ContactName] AS [ContactName],
[Extent1].[ContactTitle] AS [ContactTitle],
[Extent1].[Country] AS [Country],
[Extent1].[Fax] AS [Fax],
[Extent1].[HomePage] AS [HomePage],
[Extent1].[Phone] AS [Phone],
[Extent1].[PostalCode] AS [PostalCode],
[Extent1].[Region] AS [Region],
[Extent1].[SupplierID] AS [SupplierID]
FROM [dbo].[Suppliers] AS [Extent1]
WHERE EXISTS (SELECT
cast(1 as bit) AS [C1]
FROM [dbo].[Products] AS [Extent2]
WHERE ([Extent1].[SupplierID] = [Extent2].[SupplierID]) AND ([Extent2].[
UnitsInStock] = 0)
)
In查询当然也是不可少的。使用方法如下:
string entitySQL =
LIKE查询
@"SELECT VALUE c FROM Customers AS c WHERE c.City in {'Seattle','harbin'}";
var query = db.CreateQuery<Orders>(entitySQL);
like做为一个模糊查询的关键字是一定要支持的。
string entitySQL =
Between、And查询
@"SELECT VALUE c FROM Customers AS c WHERE c.City like '%at%';";
var query = db.CreateQuery<Orders>(entitySQL);string entitySQL =@"SELECT VALUE c FROM Customers AS c WHERE c.ID between 1 and 100";
var query = db.CreateQuery<Orders>(entitySQL);
版权与免责声明
1、本站所发布的文章仅供技术交流参考,本站不主张将其做为决策的依据,浏览者可自愿选择采信与否,本站不对因采信这些信息所产生的任何问题负责。
2、本站部分文章来源于网络,其版权为原权利人所有。由于来源之故,有的文章未能获得作者姓名,署“未知”或“佚名”。对于这些文章,有知悉作者姓名的请告知本站,以便及时署名。如果作者要求删除,我们将予以删除。除此之外本站不再承担其它责任。
3、本站部分文章来源于本站原创,本站拥有所有权利。
4、如对本站发布的信息有异议,请联系我们,经本站确认后,将在三个工作日内做出修改或删除处理。
请参阅权责声明!