linq to access 简单实现

      为了节省服务器,网站的访问量也不算太大,一直想用access数据库,但苦于linq 不支持access,在网上找了很多的方法,但觉的都不是太完美。在看了linq to sql的源码后,才发现,linq to sql 可以用于 access数据库。因为在linq to sql里面都是用的DbConnection,而不是SqlConnection,这样的话理论上可以支持所有的数据,但对于一些数据库的支持可能不是太好。例如分页,sql2000,sql2005,sql2008数据,使用linq的代码都不一样,而access和sql2000比较接近,就可以直接使用Sql2000Provider。查了一些资料看到,理论有那个数据库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.Sql2000Provider))]设定为Sql2000Provider,不然的话 linq 里面的first 不能使用,另外分页也不能使用,因为他默认的是Sql2008Provider。这一点很重要,到现在为止,基本上解决linq to access的使用,但还有一点问题,从数据库读取一条记录,修改后使用SubmitChanges()更新,提示错误,不能修改,错误内容:找不到行或行已更改。 这一点可以使用一些自定义方法来实现更新,使用ExecuteCommand()直接执行更新sql语句来实现。感觉linq to sql的跟踪,如果不适用SubmitChanges()更新的话,跟踪也每太大的意义,实现跟踪可能会降低系能,另外添加,删除也依赖跟踪,如果不使用跟踪的话,还要扩展添加,删除的方法。

 

[System.Data.Linq.Mapping.DatabaseAttribute(Name = " game1 " )]
    [Provider(
typeof (System.Data.Linq.SqlClient.Sql2000Provider))]
    
public   partial   class  dbgame : System.Data.Linq.DataContext

 

System.Data.Linq.DataContext的扩展的方法:sql to sql 类的名称dbgame

 

ContractedBlock.gif ExpandedBlockStart.gif Code
  public partial class dbgame
    {

        
public IQueryable<TEntity> Find<TEntity>(TEntity obj) where TEntity : class
        {
            
//获得所有property的信息
            PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            
//构造初始的query
         
            IQueryable
<TEntity> query = this.GetTable<TEntity>().AsQueryable<TEntity>();
            
//遍历每个property
            foreach (PropertyInfo p in properties)
            {
                
if (p != null)
                {
                    Type t 
= p.PropertyType;
                    
//加入object,Binary,和XDocument, 支持sql_variant,imager 和xml等的影射。
                    if (t.IsValueType || t == typeof(string|| t == typeof(System.Byte[])
                      
|| t == typeof(object|| t == typeof(System.Xml.Linq.XDocument)
                      
|| t == typeof(System.Data.Linq.Binary))
                    {
                        
//如果不为null才算做条件

                        
if (p.GetValue(obj, null!= null)
                        {
                            
if (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey && Convert.ToInt32(p.GetValue(obj, null)) == 0)
                            {

                            }
                            
else
                            {
                                ParameterExpression param 
= Expression.Parameter(typeof(TEntity),"c");
                                Expression right 
= Expression.Constant(p.GetValue(obj, null));
                                Expression left 
= Expression.Property(param, p.Name);
                                Expression filter 
= Expression.Equal(left, right);
                                Expression
<Func<TEntity, bool>> pred = Expression.Lambda<Func<TEntity, bool>>(filter, param);
                                query 
= query.Where(pred);
                            }
                        }
                    }
                }
            }
            
return query;
        }
        
public void Update<TEntity>(TEntity obj) where TEntity : class
        {
            
string str = "update  " + typeof(TEntity).Name + " set ";
            
string cols = "";
            
string where="";
            
//获得所有property的信息
            PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            
//构造初始的query

            IQueryable
<TEntity> query = this.GetTable<TEntity>().AsQueryable<TEntity>();
            
//遍历每个property
            foreach (PropertyInfo p in properties)
            {
                
if (p != null)
                {
                    Type t 
= p.PropertyType;
                    
//加入object,Binary,和XDocument, 支持sql_variant,imager 和xml等的影射。
                    if (t.IsValueType || t == typeof(string|| t == typeof(System.Byte[])
                      
|| t == typeof(object|| t == typeof(System.Xml.Linq.XDocument)
                      
|| t == typeof(System.Data.Linq.Binary))
                    {
                        
//如果不为null才算做条件

                        
if (p.GetValue(obj, null!= null)
                        {
                            
if (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey)
                            {
                                
where +=" where "+p.Name+"="+p.GetValue(obj,null);
                            }
                            
else
                            {
                               
                                
if (t == typeof(System.Byte[]) || t == typeof(System.Int32) || t == typeof(Double) || t == typeof(float))
                                    cols 
+= p.Name + "=" + p.GetValue(obj, null+ ",";
                                
else
                                    cols 
+= p.Name + "='" + p.GetValue(obj, null+ "',";
                            }
                        }
                    }
                }
            }

            str 
+= cols.Substring(0,cols.Length-1+where;
            HttpContext.Current.Response.Write(
"<br>"+str+"<br>");
             
this.ExecuteCommand(str);
          
        }
        
public void Insert<TEntity>(TEntity obj) where TEntity : class
        {
            
string str = "insert into [" + typeof(TEntity).Name + "] (";
            
string cols = "";
            
string vals = "";
            
string where = "";
            
//获得所有property的信息
            PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            
//构造初始的query

            IQueryable
<TEntity> query = this.GetTable<TEntity>().AsQueryable<TEntity>();
            
//遍历每个property
            foreach (PropertyInfo p in properties)
            {
                
if (p != null)
                {
                    Type t 
= p.PropertyType;
                    
//加入object,Binary,和XDocument, 支持sql_variant,imager 和xml等的影射。
                    if (t.IsValueType || t == typeof(string|| t == typeof(System.Byte[])
                      
|| t == typeof(object|| t == typeof(System.Xml.Linq.XDocument)
                      
|| t == typeof(System.Data.Linq.Binary))
                    {
                        
//如果不为null才算做条件

                        
if (p.GetValue(obj, null!= null)
                        {
                            
//if (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey && Convert.ToInt32(p.GetValue(obj,null))==0)
                            
//{
                                
                            
//}
                            
//else
                            
//{
                                cols += "["+p.Name + "],";
                                
if (t == typeof(System.Byte[]) || t == typeof(System.Int32) || t == typeof(Double) || t == typeof(float))
                                    vals 
+= p.GetValue(obj, null+ ",";
                                
else
                                    vals 
+="'"+ p.GetValue(obj, null+ "',";
                           
// }
                        }
                    }
                }
            }

            str 
+= cols.Substring(0, cols.Length - 1+ ") values (" + vals.Substring(0, vals.Length - 1+ ")";
            HttpContext.Current.Response.Write(
"<br>" + str + "<br>");
            
this.ExecuteCommand(str);

        }
        
public void Delete<TEntity>(TEntity obj) where TEntity : class
        {
            
string str = "delete from [" + typeof(TEntity).Name+"] where ";
            
string cols = "";
            
string where = "";
            
//获得所有property的信息
            PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            
//构造初始的query

            IQueryable
<TEntity> query = this.GetTable<TEntity>().AsQueryable<TEntity>();
            
//遍历每个property
            foreach (PropertyInfo p in properties)
            {
                
if (p != null)
                {
                    Type t 
= p.PropertyType;
                    
//加入object,Binary,和XDocument, 支持sql_variant,imager 和xml等的影射。
                    if (t.IsValueType || t == typeof(string|| t == typeof(System.Byte[])
                      
|| t == typeof(object|| t == typeof(System.Xml.Linq.XDocument)
                      
|| t == typeof(System.Data.Linq.Binary))
                    {
                        
//如果不为null才算做条件

                        
if (p.GetValue(obj, null!= null)
                        {
                            
if (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey && Convert.ToInt32(p.GetValue(obj, null)) == 0)
                            {

                             }
                            
else
                            {
                                
if (t == typeof(System.Byte[]) || t == typeof(System.Int32) || t == typeof(Double) || t == typeof(float))
                                    
where +="["+p.Name+"]" + "=" + p.GetValue(obj, null+ " and ";
                                
else
                                    
where += "[" + p.Name + "]" + "='" + p.GetValue(obj, null+ "' and ";
                            }
                        }
                    }
                }
            }

            str 
+=where.Substring(0,where.Length-5);
            HttpContext.Current.Response.Write(
"<br>" + str + "<br>");
            
this.ExecuteCommand(str);

        }
        
public IQueryable<TEntity> FindKey<TEntity>(object value) where TEntity : class
        {
            
//获得所有property的信息
            PropertyInfo[] properties = typeof(TEntity).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            
//构造初始的query
            IQueryable<TEntity> query = this.GetTable<TEntity>().AsQueryable<TEntity>();
            
//遍历每个property
            foreach (PropertyInfo p in properties)
            {
                
if (p != null)
                {
                    Type t 
= p.PropertyType;
                    
//加入object,Binary,和XDocument, 支持sql_variant,imager 和xml等的影射。
                    if (t.IsValueType || t == typeof(string|| t == typeof(System.Byte[])
                      
|| t == typeof(object|| t == typeof(System.Xml.Linq.XDocument)
                      
|| t == typeof(System.Data.Linq.Binary))
                    {
                        
//如果不为null才算做条件


                        
if (((ColumnAttribute)(p.GetCustomAttributes(typeof(ColumnAttribute), true)[0])).IsPrimaryKey)
                        {
                            ParameterExpression param 
= Expression.Parameter(typeof(TEntity), "d");
                            Expression right 
= Expression.Constant(value);
                            Expression left 
= Expression.Property(param, p.Name);
                            Expression filter 
= Expression.Equal(left, right);

                            Expression
<Func<TEntity, bool>> pred = Expression.Lambda<Func<TEntity, bool>>(filter, param);

                            query 
= query.Where(pred);
                            
break;

                        }




                    }
                }
            }
            
return query;
        }



    }

 

没有解决的问题:

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

 

转载于:https://www.cnblogs.com/wangjikun3/archive/2009/06/18/linqoaccess.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值