首页 > 代码库 > C# EF 基础操作

C# 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();
        }
    }
}

 

C# EF 基础操作