大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > C#技巧 > 让ADO.NET Entity Framework 支持AC

让ADO.NET Entity Framework 支持AC(5)

关键词:数据库.NETADOEntity  阅读(1897) 赞(16)

[摘要]本文是对让ADO.NET Entity Framework 支持ACCESS数据库的讲解,与大家分享。

public int AutoUpdate()
        {
            List<string> ArrSqlText = new List<string>();
            foreach (KeyValuePair<string, Dictionary<string, Dictionary<string, object[]>>> TabKVP in m_ArrDetection)
            {
                //遍历表名
                string TabName = TabKVP.Key;
                foreach (KeyValuePair<string, Dictionary<string, object[]>> KeyKVP in TabKVP.Value)
                {
                    string strSet = "";
                    string strMainKeyName = "";
                    #region 把数据列出来例如: a=1,c="2"
                    foreach (KeyValuePair<string, object[]> ValueKVP in KeyKVP.Value)
                    {
                        if (strMainKeyName.Length == 0) strMainKeyName = ValueKVP.Value[1].ToString();
                        object Va = ValueKVP.Value[0];
                        string strLeft = ValueKVP.Key;
                        string strRight = "";
                        #region 根据值确认是否添加引号
                        if (ValueKVP.Value == null)
                            continue;
                        else if (Va is DateTime)
                            strRight = string.Format("#{0}#", Va.ToString());
                        else if (Va is ValueType)
                            strRight = Va.ToString();
                        else if (Va is string || Va is char)
                            strRight = string.Format("'{0}'", Va.ToString());
                        #endregion
                        if (strRight.Length == 0) continue;
                        if (strLeft == "EntityKey" || strLeft == "EntityState") continue;
                        strSet += strLeft + "=" + strRight + ",";

                    }
                    #endregion
                    if (strSet.Length < 2) continue;
                    strSet = strSet.Remove(strSet.Length - 1);
                    //根据当前的主键[ID] 生成一个SQL语句
                    string strSqlQuery = string.Format("UPDATE {0} SET {1} WHERE {2}={3} ", TabName, strSet, strMainKeyName, KeyKVP.Key);
                    ArrSqlText.Add(strSqlQuery);
                }
            }
            foreach (string strSqlQuery in ArrSqlText)
            {
                m_LastSqlCommand = strSqlQuery;
                try
                {
                    OleDbCommand Cmd = new OleDbCommand(strSqlQuery, AccessConn);
                    Cmd.ExecuteNonQuery();
                }
                catch
                {
                }

            }
            return 0;
        }

当然我们还有直接把对象直接赋值拷贝的时候( a = b),这时候是侦测不到属性的变化的,所以我们要另外一个函数来支持更新,就是让他实现侦测到属性的变化。

public void CopyPropertiesFrom(object destObject, object sourceObject)
        {
            if (destObject.GetType().Name != destObject.GetType().Name) throw new Exception("类型不同");
            PropertyInfo[] destProperties = destObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            PropertyInfo[] sourceProperties = sourceObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            PropertyInfo EntityKey = GetEntityKeyFormAllProperty(destProperties);
            if (EntityKey == null) throw new Exception("未设置主键,无法使用本函数请使用其他函数!");
            
            for (int i = 0; i < destProperties.Length; i++)
            {
                if (destProperties[i]==null|| destProperties[i].Name == EntityKey.Name) continue;
                if (destProperties[i].Name == "EntityKey" || destProperties[i].Name == "EntityState") continue;
                object DstV = destProperties[i].GetValue(destObject,null);
                object SrcV = sourceProperties[i].GetValue(sourceObject, null);
                if (SrcV == null) continue;//源 是NULL 不拷贝
                if (DstV.ToString() == SrcV.ToString()) continue;
                destProperties[i].SetValue(destObject, SrcV,null);
                //Action<object, object> LmdSetProp = LmdSet(destObject.GetType(), destProperties[i].Name);
                //LmdSetProp(destObject, SrcV);
            }

        }

显示-添加-删除-修改的例子代码

#region 显示用户
        [Authorize(Roles = "manager")]
        public ActionResult Index()
        {
            List<Users> Users = new List<Users>();
            Users u = new Users();
            try
            {
                using (SqlDoorEntities Database = new SqlDoorEntities())
                {
                    IEnumerable<Users> Records = Database.Users;
                    if (Records.Count() > 0)
                    {
                        foreach (Users U in Records) Users.Add(U);
                    }
                }
            }
            catch { }
            return View(Users);
        }
        #endregion

        #region 创建用户
        [Authorize(Roles = "manager")]
        [HttpPost]
        public ActionResult CreateUser(Users collection)
        {
            try
            {
                // TODO: Add insert logic here
                using (SqlDoorEntities Database = new SqlDoorEntities())
                {
                    IEnumerable<Users> Records = Database.Where<Users>(R => R.U_Number == collection.U_Number);
                    if (Records.Count() > 0)
                    {
                        ModelState.AddModelError("", "已經有了記錄了!");
                        return RedirectToAction("Index");
                    }
                    Database.AddToUsers(collection);
                    Database.SaveChanges();
                    //collection.U_LastIP = GetWebClientIp();
                }
                return RedirectToAction("Index");
            }
            catch (Exception E)
            {
                ModelState.AddModelError("", "数据库错误!" + E.Message);
            }
            return View();
        }
        [Authorize(Roles = "manager")]
        public ActionResult CreateUser()
        {
            return View();
        }
        #endregion

        #region 编辑用户
        [Authorize(Roles = "manager")]
        [HttpPost]
        public ActionResult EditUser(int id, Users collection)
        {
            try
            {
                // TODO: Add insert logic here
                
                using (SqlDoorEntities Database = new SqlDoorEntities())
                {
                    Users Record = Database.Where<Users>(R => R.U_ID == id).FirstOrDefault();
                    //Database.Update<Users>(Record);
                    Database.CopyPropertiesFrom(Record, collection);
                    Database.SaveChanges();
                }
                return Content("OK");
            }
            catch (Exception E)
            {
                return Content(E.Message);
            }
        }
        #endregion

        #region 删除用户
        [Authorize(Roles = "manager")]
        public ActionResult DeleteUser(int id)
        {
            try
            {
                // TODO: Add insert logic here

                using (SqlDoorEntities Database = new SqlDoorEntities())
                {
                    Users Record = Database.Where<Users>(R => R.U_ID == id).FirstOrDefault();
                    if (User != null)
                    {
                        Database.DeleteObject(Record);
                        Database.SaveChanges();
                    }
                }
            }
            catch
            {

            }
            return RedirectToAction("Index");
        }
        #endregion

最后

下面是用到的源文件。

http://files.cnblogs.com/hackdragon/EFToAccess.zip

«上一页12345下一页»


相关评论