zoukankan      html  css  js  c++  java
  • c#.net ef 框架的基础操作

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Reflection;
    
    namespace MCO.EF
    {
        public class Test
        {
            //实例化上下文
            ConnectionSQL connection = new ConnectionSQL();
            //增加
            public int DataAdd()
            {
                User user = new User()
                {
                    UserName = "陆六",
                    UserSex = true
                };
                connection.User.Add(user);
                return connection.SaveChanges();
            }
            //删除
            public int Delete()
            {
                List<User> user = connection.User.Where<User>(u => u.UserId > 2).ToList<User>();
                foreach(User u in user)
                {
                    connection.User.Remove(u);
                }
                return connection.SaveChanges();
            }
            //修改
            public int Update()
            {
                List<User> user =  connection.User.Where<User>(u => u.UserSex == true).ToList<User>();
                foreach(User u in user)
                {
                    u.UserSex = false;
                }
                return connection.SaveChanges();
            }
            //查询
            private void UserList()
            {
                IQueryable userList = connection.User.Where<User>(u => u.UserId > 1);
                //反射获取实体类的所有属性值和属性名
                PropertyInfo[] attribute = typeof(User).GetProperties();
                //调用 ListToJson 方法
                Console.Write(ListToJson(attribute, userList));
            }
            //反射拼接成 json
            private string ListToJson(PropertyInfo[] attribute, IQueryable dataList)
            {
                StringBuilder strJson = new StringBuilder(256);
                foreach(var data in dataList)
                {
                    strJson.Append("{");
                    for(int i = 0; i < attribute.Length; i++)
                    {
                        //获取属性名 和 属性值(通过反射)
                        strJson.AppendFormat(""{0}":"{1}",", attribute[i].Name, attribute[i].GetValue(data));
                    }
                    strJson.Remove(strJson.Length - 1, 1);
                    strJson.Append("},");
                }
                strJson.Remove(strJson.Length - 1, 1);
                return strJson.ToString();
            }
        }
    }
  • 相关阅读:
    X 如何在mysql客户端即mysql提示符下执行操作系统命令
    X MySQL UNDO表空间独立和截断 ,mysql undo 的历史
    X Mysql5.7忘记root密码及mysql5.7修改root密码的方法
    X mysql密码的安全策略ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
    二分法查找
    elasticsearch API
    logstash的基础
    elasticsearch的基础
    Linux的进程管理
    Linux的网卡配置
  • 原文地址:https://www.cnblogs.com/lovling/p/6441866.html
Copyright © 2011-2022 走看看