Linq To Sql进阶系列(六)用object的动态查询与保存log篇
[1] Linq To Sql进阶系列(六)用object的动态查询与保存log篇
[2] Linq To Sql进阶系列(六)用object的动态查询与保存log篇
[3] Linq To Sql进阶系列(六)用object的动态查询与保存log篇
[2] Linq To Sql进阶系列(六)用object的动态查询与保存log篇
[3] Linq To Sql进阶系列(六)用object的动态查询与保存log篇
系列文章导航:
Linq To Sql进阶系列(四)User Define Function篇
Linq To Sql进阶系列(五)Store Procedure篇
Linq To Sql进阶系列(六)用object的动态查询与保存log篇
Linq To Sql进阶系列(七)动态查询续及CLR与SQL在某些细节上的差别
4,测试用例及反思
我们用下面的例子来测试下这个函数
Customer c = new Customer();
c.City = "London";
c.Phone = "23236133";
var q = db.Find<Customer>(c).ToList();
c.City = "London";
c.Phone = "23236133";
var q = db.Find<Customer>(c).ToList();
其生成的sql语句为:
SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle],
[t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone],
[t0].[Fax]
FROM [dbo].[Customers] AS [t0]
WHERE ([t0].[Phone] = @p0) AND ([t0].[City] = @p1)
-- @p0: Input NVarChar (Size = 8; Prec = 0; Scale = 0) [23236133]
-- @p1: Input NVarChar (Size = 6; Prec = 0; Scale = 0) [London]
[t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone],
[t0].[Fax]
FROM [dbo].[Customers] AS [t0]
WHERE ([t0].[Phone] = @p0) AND ([t0].[City] = @p1)
-- @p0: Input NVarChar (Size = 8; Prec = 0; Scale = 0) [23236133]
-- @p1: Input NVarChar (Size = 6; Prec = 0; Scale = 0) [London]
我们可以看到,其sql语句中,只有city和phone两个条件。并且他们之间是and的关系。我们最开始的设想实现了,但是,它是完美的吗?如果是or条件该怎么办呢?更多的时候,我们是在用模糊查询,那又该怎么办呢?这个问题,就留于下篇。
最后,介绍一种写log的方法。stream流使用static为避免多个datacontext的同时在使用log.txt文件。
partial class DataMappingDataContext
{
private static StreamWriter sw = new StreamWriter(Path.Combine(Directory.
GetCurrentDirectory(), "log.txt"),true);
/// <summary>
/// Try to create DataContext with log.
/// </summary>
/// <param name="withLog"></param>
public DataMappingDataContext(bool withLog)
: this()
{
OnCreated();
if (withLog)
{
if (sw == null)
{
sw = new StreamWriter(Path.Combine(Directory.GetCurrentDirectory(), "log.txt"),
true);
}
this.Log = sw;
}
}
/// <summary>
/// try to close streamwriter
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
sw.Flush();
}
}
{
private static StreamWriter sw = new StreamWriter(Path.Combine(Directory.
GetCurrentDirectory(), "log.txt"),true);
/// <summary>
/// Try to create DataContext with log.
/// </summary>
/// <param name="withLog"></param>
public DataMappingDataContext(bool withLog)
: this()
{
OnCreated();
if (withLog)
{
if (sw == null)
{
sw = new StreamWriter(Path.Combine(Directory.GetCurrentDirectory(), "log.txt"),
true);
}
this.Log = sw;
}
}
/// <summary>
/// try to close streamwriter
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
sw.Flush();
}
}
在dispose函数里,把输出流flush。使用时,如下
using(northwind db = new norhwind(true))
{
//do something......
}
好,就先讲到这里。