浅谈LINQ to ACCESS简单实现

开发 后端
为了节省服务器,网站的访问量也不算太大,一直想用ACCESS数据库,但苦于LINQ不支持ACCESS,在网上找了很多的方法,但觉的都不是太完美。在看了LINQ to ACCESS的源码后,才发现,linq to sql 可以用于ACCESS数据库。

在LINQ to SQL里面都是用的DbConnection,而不是SQLConnection,这样的话理论上可以支持所有的数据,但对于一些数据库的支持可能不是太好。例如分页,SQL Server 2000,SQL Server 2005,SQL Server 2008数据,使用LINQ的代码都不一样,而ACCESS和SQL Server 2000比较接近,就可以直接使用SQL Server 2000Provider。查了一些资料看到,理论有那个数据库provider,就可以支持这种数据库。也看了dbLINQ 0.8支持不同数据库的源码,但自己能力有限不能写一个ACCESS的,还是用官方的吧。下边说一下方法。

其实他不太麻烦,只是改一下,*.designer.cs文件里的代码。因为ACCESS 不支持dbo,而LINQ to SQL里数据表前面都有dbo.的前缀, [Table(Name="dbo.wjk3")],将dbo.去掉,不然的话,会提示你找不到dbo数据库,这点上,自己走了不少弯路。在public partial class DDataContext: System.Data.LINQ.DataContext上边加上, [Provider(typeof(System.Data.LINQ.SQLClient.SQL Server 2000Provider))]设定为SQL Server 2000Provider,不然的话 LINQ 里面的first 不能使用,另外分页也不能使用,因为他默认的是SQL Server 2008Provider。

这一点很重要,到现在为止,基本上解决LINQ to ACCESS的使用,但还有一点问题,从数据库读取一条记录,修改后使用SubmitChanges()更新,提示错误,不能修改,错误内容:找不到行或行已更改。这一点可以使用一些自定义方法来实现更新,使用ExecuteCommand()直接执行更新SQL语句来实现。感觉LINQ to SQL的跟踪,如果不适用SubmitChanges()更新的话,跟踪也每太大的意义,实现跟踪可能会降低系能,另外添加,删除也依赖跟踪,如果不使用跟踪的话,还要扩展添加,删除的方法。

  1. public partial class dbgame  
  2.     {  
  3.         public IQueryable<TEntity> Find<TEntity>(TEntity obj) where TEntity : class  
  4.         {  
  5.             //获得所有property的信息  
  6.             PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  7.             //构造初始的query  
  8.             IQueryable<TEntity> query = this.GetTable<TEntity>().AsQueryable<TEntity>();  
  9.             //遍历每个property  
  10.             foreach (PropertyInfo p in properties)  
  11.             {  
  12.                 if (p != null)  
  13.                 {  
  14.                     Type t = p.PropertyType;  
  15.                     //加入object,Binary,和XDocument, 支持sql_variant,imager 和xml等的影射。  
  16.                     if (t.IsValueType || t == typeof(string) || t == typeof(System.Byte[])  
  17.                       || t == typeof(object) || t == typeof(System.Xml.Linq.XDocument)  
  18.                       || t == typeof(System.Data.Linq.Binary))  
  19.                     {  
  20.                         //如果不为null才算做条件  
  21.                         if (p.GetValue(obj, null) != null)  
  22.                         {  
  23.                             if (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey && Convert.ToInt32(p.GetValue(obj, null)) == 0)  
  24.                             {  
  25.                             }  
  26.                             else  
  27.                             {  
  28.                                 ParameterExpression param = Expression.Parameter(typeof(TEntity),"c");  
  29.                                 Expression right = Expression.Constant(p.GetValue(obj, null));  
  30.                                 Expression left = Expression.Property(param, p.Name);  
  31.                                 Expression filter = Expression.Equal(left, right);  
  32.                                 Expression<Func<TEntity, bool>> pred = Expression.Lambda<Func<TEntity, bool>>(filter, param);  
  33.                                 queryquery = query.Where(pred);  
  34.                             }  
  35.                         }  
  36.                     }  
  37.                 }  
  38.             }  
  39.             return query;  
  40.         }  
  41.         public void Update<TEntity>(TEntity obj) where TEntity : class  
  42.         {  
  43.             string str = "update  " + typeof(TEntity).Name + " set ";  
  44.             string cols = "";  
  45.             string where="";  
  46.             //获得所有property的信息  
  47.             PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  48.             //构造初始的query  
  49.  
  50.             IQueryable<TEntity> query = this.GetTable<TEntity>().AsQueryable<TEntity>();  
  51.             //遍历每个property  
  52.             foreach (PropertyInfo p in properties)  
  53.             {  
  54.                 if (p != null)  
  55.                 {  
  56.                     Type t = p.PropertyType;  
  57.                     //加入object,Binary,和XDocument, 支持sql_variant,imager 和xml等的影射。  
  58.                     if (t.IsValueType || t == typeof(string) || t == typeof(System.Byte[])  
  59.                       || t == typeof(object) || t == typeof(System.Xml.Linq.XDocument)  
  60.                       || t == typeof(System.Data.Linq.Binary))  
  61.                     {  
  62.                         //如果不为null才算做条件  
  63.  
  64.                         if (p.GetValue(obj, null) != null)  
  65.                         {  
  66.                             if (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey)  
  67.                             {  
  68.                                 where +=" where "+p.Name+"="+p.GetValue(obj,null);  
  69.                             }  
  70.                             else  
  71.                             {  
  72.                                  
  73.                                 if (t == typeof(System.Byte[]) || t == typeof(System.Int32) || t == typeof(Double) || t == typeof(float))  
  74.                                     cols += p.Name + "=" + p.GetValue(obj, null) + ",";  
  75.                                 else  
  76.                                     cols += p.Name + "='" + p.GetValue(obj, null) + "',";  
  77.                             }  
  78.                         }  
  79.                     }  
  80.                 }  
  81.             }  
  82.  
  83.             str += cols.Substring(0,cols.Length-1) +where;  
  84.             HttpContext.Current.Response.Write("<br>"+str+"<br>");  
  85.              this.ExecuteCommand(str);  
  86.             
  87.         }  
  88.         public void Insert<TEntity>(TEntity obj) where TEntity : class  
  89.         {  
  90.             string str = "insert into [" + typeof(TEntity).Name + "] (";  
  91.             string cols = "";  
  92.             string vals = "";  
  93.             string where = "";  
  94.             //获得所有property的信息  
  95.             PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  96.             //构造初始的query  
  97.  
  98.             IQueryable<TEntity> query = this.GetTable<TEntity>().AsQueryable<TEntity>();  
  99.             //遍历每个property  
  100.             foreach (PropertyInfo p in properties)  
  101.             {  
  102.                 if (p != null)  
  103.                 {  
  104.                     Type t = p.PropertyType;  
  105.                     //加入object,Binary,和XDocument, 支持sql_variant,imager 和xml等的影射。  
  106.                     if (t.IsValueType || t == typeof(string) || t == typeof(System.Byte[])  
  107.                       || t == typeof(object) || t == typeof(System.Xml.Linq.XDocument)  
  108.                       || t == typeof(System.Data.Linq.Binary))  
  109.                     {  
  110.                         //如果不为null才算做条件  
  111.  
  112.                         if (p.GetValue(obj, null) != null)  
  113.                         {  
  114.                             //if (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey && Convert.ToInt32(p.GetValue(obj,null))==0)  
  115.                             //{  
  116.                                   
  117.                             //}  
  118.                             //else  
  119.                             //{  
  120.                                 cols += "["+p.Name + "],";  
  121.                                 if (t == typeof(System.Byte[]) || t == typeof(System.Int32) || t == typeof(Double) || t == typeof(float))  
  122.                                     vals += p.GetValue(obj, null) + ",";  
  123.                                 else  
  124.                                     vals +="'"+ p.GetValue(obj, null) + "',";  
  125.                            // }  
  126.                         }  
  127.                     }  
  128.                 }  
  129.             }  
  130.  
  131.             str += cols.Substring(0, cols.Length - 1) + ") values (" + vals.Substring(0, vals.Length - 1) + ")";  
  132.             HttpContext.Current.Response.Write("<br>" + str + "<br>");  
  133.             this.ExecuteCommand(str);  
  134.  
  135.         }  
  136.         public void Delete<TEntity>(TEntity obj) where TEntity : class  
  137.         {  
  138.             string str = "delete from [" + typeof(TEntity).Name+"] where ";  
  139.             string cols = "";  
  140.             string where = "";  
  141.             //获得所有property的信息  
  142.             PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  143.             //构造初始的query  
  144.  
  145.             IQueryable<TEntity> query = this.GetTable<TEntity>().AsQueryable<TEntity>();  
  146.             //遍历每个property  
  147.             foreach (PropertyInfo p in properties)  
  148.             {  
  149.                 if (p != null)  
  150.                 {  
  151.                     Type t = p.PropertyType;  
  152.                     //加入object,Binary,和XDocument, 支持sql_variant,imager 和xml等的影射。  
  153.                     if (t.IsValueType || t == typeof(string) || t == typeof(System.Byte[])  
  154.                       || t == typeof(object) || t == typeof(System.Xml.Linq.XDocument)  
  155.                       || t == typeof(System.Data.Linq.Binary))  
  156.                     {  
  157.                         //如果不为null才算做条件  
  158.  
  159.                         if (p.GetValue(obj, null) != null)  
  160.                         {  
  161.                             if (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey && Convert.ToInt32(p.GetValue(obj, null)) == 0)  
  162.                             {  
  163.  
  164.                              }  
  165.                             else  
  166.                             {  
  167.                                 if (t == typeof(System.Byte[]) || t == typeof(System.Int32) || t == typeof(Double) || t == typeof(float))  
  168.                                     where +="["+p.Name+"]" + "=" + p.GetValue(obj, null) + " and ";  
  169.                                 else  
  170.                                     where += "[" + p.Name + "]" + "='" + p.GetValue(obj, null) + "' and ";  
  171.                             }  
  172.                         }  
  173.                     }  
  174.                 }  
  175.             }  
  176.  
  177.             str +=where.Substring(0,where.Length-5);  
  178.             HttpContext.Current.Response.Write("<br>" + str + "<br>");  
  179.             this.ExecuteCommand(str);  
  180.  
  181.         }  
  182.         public IQueryable<TEntity> FindKey<TEntity>(object value) where TEntity : class  
  183.         {  
  184.             //获得所有property的信息  
  185.             PropertyInfo[] properties = typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  186.             //构造初始的query  
  187.             IQueryable<TEntity> query = this.GetTable<TEntity>().AsQueryable<TEntity>();  
  188.             //遍历每个property  
  189.             foreach (PropertyInfo p in properties)  
  190.             {  
  191.                 if (p != null)  
  192.                 {  
  193.                     Type t = p.PropertyType;  
  194.                     //加入object,Binary,和XDocument, 支持sql_variant,imager 和xml等的影射。  
  195.                     if (t.IsValueType || t == typeof(string) || t == typeof(System.Byte[])  
  196.                       || t == typeof(object) || t == typeof(System.Xml.Linq.XDocument)  
  197.                       || t == typeof(System.Data.Linq.Binary))  
  198.                     {  
  199.                         //如果不为null才算做条件  
  200.                         if (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey)  
  201.                         {  
  202.                             ParameterExpression param = Expression.Parameter(typeof(TEntity), "d");  
  203.                             Expression right = Expression.Constant(value);  
  204.                             Expression left = Expression.Property(param, p.Name);  
  205.                             Expression filter = Expression.Equal(left, right);  
  206.  
  207.                             Expression<Func<TEntity, bool>> pred = Expression.Lambda<Func<TEntity, bool>>(filter, param);  
  208.  
  209.                             queryquery = query.Where(pred);  
  210.                            break;  
  211.                         }  
  212.                     }  
  213.                 }  
  214.             }  
  215.             return query;  
  216.         }  
  217.     } 

没有解决的问题:

怎样能解决更新的时候能直接使用SubmitChanges();

【编辑推荐】

  1. 使用LINQ查询泛型字典Dictionary
  2. 浅析Linq to SQL更新数据时容易忽略的问题
  3. 浅谈LINQ to SQL集成数据库语言优劣
  4. LINQ横向对比foreach方法
  5. 浅谈LINQ如何插入删除和更新数据库记录备注
责任编辑:彭凡 来源: cnblogs
相关推荐

2009-09-08 10:03:13

Linq查询Acces

2009-09-08 16:55:01

Linq实现XML转换

2009-09-17 09:24:57

Linq实现分页

2009-09-15 15:18:40

Linq连接查询

2009-09-09 15:44:22

Linq DataCo

2009-09-15 16:31:15

LINQ Custom

2009-09-15 11:34:47

Linq多条件查询

2009-09-10 15:45:07

Linq使用Selec

2009-09-10 11:29:00

LINQ to SQL

2009-09-11 11:25:35

LINQ函数集合

2009-09-16 11:15:52

Linq联接数据

2009-09-07 17:32:14

LINQ检索数据

2009-09-14 09:49:08

Linq扩展函数

2009-09-08 15:19:52

Linq Where操

2009-09-17 09:57:08

linq创建数据库

2009-09-17 10:40:23

linq存储过程

2009-09-18 16:32:51

Linq委托实例化

2009-09-14 15:45:28

LINQ删除XML节点

2009-09-15 11:08:01

LinQ调用存储过程

2009-09-09 11:07:52

LINQ to SQL
点赞
收藏

51CTO技术栈公众号