房租管理小软件(四):对linq的使用

1.对LInq的封装如下:

    private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
public static MyFZDataContext a = null;
static String path = Application.StartupPath;
public MyFZDataContext(): base(getConnstring(), mappingSource)
{ } public MyFZDataContext(bool b): base(getConnstring(), mappingSource)
{
this.ObjectTrackingEnabled = b;
} public static string connstring = "";
public static XmlSerialize xml = new XmlSerialize();
public static Common.Setting set = xml.DeSerialize(); public static string getConnstring()
{
String Ip = set.IP;
string user = set.User;
string pass = set.Password;
string DB = set.DB;
connstring = "Data Source=" + Ip + ";Initial Catalog=" + DB + ";Persist Security Info=True;User ID=" + user + ";Password=" + pass + "" + ";Application Name=" + "NetHotel";
return connstring;
} public static MyFZDataContext getDataContext()
{
if (a == null)
{ a = new MyFZDataContext(false);
}
return a; }

2.在代码中使用时加入

 using System.Data.Linq;
using System.Linq;
using DataBase;

3.一个从数据库,得到数据的例子

 MyFZDataContext dataContext = new MyFZDataContext();
var v1 = from t in dataContext.VIEW_LD
where
t.账号.Contains(textEdit_Search.Text) ||
t.手机.Contains(textEdit_Search.Text) ||
t.承租人.Contains(textEdit_Search.Text)
select t;
DataTable dt = DataFunction.LINQToDataTable(v1);
this.gridControl1.DataSource = dt;

4.事务的使用

 #region 增加//增加
MyFZDataContext dataContext = new MyFZDataContext();
if (dataContext.Connection != null) { dataContext.Connection.Open(); }
System.Data.Common.DbTransaction tran = dataContext.Connection.BeginTransaction();
dataContext.Transaction = tran;
try
{
dataContext.SubmitChanges(); tran.Commit();
MessageBox.Show("保存成功");
this.Close();
}
catch (Exception ex)
{ tran.Rollback();
MessageBox.Show(ex.Message);
}
#endregion

5.把得到数据转成dataTable

 public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable(); // column names
PropertyInfo[] oProps = null; if (varlist == null) return dtReturn; foreach (T rec in varlist)
{
//// Use reflection to get property names, to create table, Only first time, others
//will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
== typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[];
} dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
} DataRow dr = dtReturn.NewRow(); foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
(rec, null);
} dtReturn.Rows.Add(dr);
}
return dtReturn;
}
上一篇:angular遇到问题


下一篇:wrk中的lua脚本(转)