EF 一个简单的使用

原文:https://www.cnblogs.com/leotsai/p/entity-framework-doesnt-need-additional-repository.html

花猫.NET的评论里面的代码

记录一下

 

 

1、创建的控制台程序,NuGet引用了EF。  里面用了序列号,需要引用Newtonsoft.Json

2、数据库用的现成的,已经有表和数据了。数据库名MyDbContext,表Students

3、在app.config中添加配置项,添加到configSections这个节点后面,和它同级。

<connectionStrings>
    <add name="MyDbContext" connectionString="Data Source=.\sqlexpress;Database=MyDbContext;UID=sa;PWD=sa;" providerName="System.Data.SqlClient"></add>
</connectionStrings>

 

 

全部代码

 

 

基本使用

//基本使用
    public class Class4
    {
        public void test1()
        {
            Console.WriteLine(123);
            using (var db = DbFactory.Create())
            {
                //db....
                //db.SaveChange();


                //测试1 打印students表的所有数据
                var list = db.All<Students>().ToList();
                var str = JsonConvert.SerializeObject(list);
                Console.WriteLine(str);


                //测试2 添加一个学生
                Students student1 = new Students
                {
                    Name = "name12",
                    Age = 12,
                };
                db.Insert<Students>(student1);
                db.SaveChanges();
            }
        }
    }
View Code

 

 

自定义代码

    //自定义代码
    public class Students
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime? CreateTime { get; set; }
    }
    
    public class MyDbContext : DbContext
    {
        public MyDbContext(string connectionName) : base(connectionName) { }
        public DbSet<Students> Orders { get; set; }
    }
View Code

 

 

通用代码 引用了 MyDbContext

    //原文:https://www.cnblogs.com/leotsai/p/entity-framework-doesnt-need-additional-repository.html
    //花猫.NET的评论里面的代码

    //通用代码 引用了 MyDbContext
    public class DbFactory
    {
        public static IRepository Create()
        {
            return new EfRepository(new MyDbContext("MyDbContext"));
        }
    }

    public interface IRepository : IDisposable
    {
        int SaveChanges();
        IQueryable<T> All<T>() where T : class;
        T Get<T>(Expression<Func<T, bool>> conditions) where T : class;
        void Insert<T>(T entity) where T : class;
        void Update<T>(T entity) where T : class;
        void Delete<T>(T entity) where T : class;
        void Delete<T>(Expression<Func<T, bool>> conditions) where T : class;
        List<T> Find<T>(Expression<Func<T, bool>> conditions = null) where T : class;
        List<T> Find<T, S>(Expression<Func<T, bool>> conditions, Expression<Func<T, S>> orderBy, int pageSize, int pageIndex, out int totalCount) where T : class;
        List<T> SqlQuery<T>(string sql);
        int ExecuteSqlCommand(string sql);
        long GetNextSequenceValue(string sequenceName);
    }

    public class EfRepository : IRepository
    {
        private DbContext context;

        public EfRepository(DbContext dbcontext)
        {
            context = dbcontext;
        }

        #region IRepository

        public IQueryable<T> All<T>() where T : class
        {
            return context.Set<T>().AsNoTracking();
        }

        public void Update<T>(T entity) where T : class
        {
            var entry = context.Entry(entity);
            if (entry.State == EntityState.Detached)
            {
                context.Set<T>().Attach(entity);
            }
            entry.State = EntityState.Modified;
        }

        public void Insert<T>(T entity) where T : class
        {
            context.Set<T>().Add(entity);
        }

        public void Delete<T>(T entity) where T : class
        {
            var entry = context.Entry(entity);
            if (entry.State == EntityState.Detached)
            {
                context.Set<T>().Attach(entity);
            }
            entry.State = EntityState.Deleted;
            context.Set<T>().Remove(entity);
        }

        public void Delete<T>(Expression<Func<T, bool>> conditions) where T : class
        {
            var list = Find<T>(conditions);
            foreach (var item in list)
            {
                Delete<T>(item);
            }

        }

        public T Get<T>(Expression<Func<T, bool>> conditions) where T : class
        {
            return All<T>().FirstOrDefault(conditions);
        }

        public List<T> Find<T>(Expression<Func<T, bool>> conditions = null) where T : class
        {
            if (conditions != null)
            {
                return All<T>().Where(conditions).ToList();
            }
            else
            {
                return All<T>().ToList();
            }

        }

        public List<T> Find<T, S>(Expression<Func<T, bool>> conditions, Expression<Func<T, S>> orderBy, int pageSize, int pageIndex, out int totalCount) where T : class
        {
            var queryList = conditions == null ?
                All<T>() :
                All<T>().Where(conditions);

            totalCount = queryList.Count();

            return queryList.OrderByDescending(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        public List<T> SqlQuery<T>(string sql)
        {
            return context.Database.SqlQuery<T>(sql).ToList();
        }



        public int ExecuteSqlCommand(string sql)
        {
            return context.Database.ExecuteSqlCommand(sql);
        }

        public int SaveChanges()
        {
            return context.SaveChanges();
        }

        public void Dispose()
        {
            context.Dispose();
        }

        public long GetNextSequenceValue(string sequenceName)
        {
            var rawQuery = context.Database.SqlQuery<long>(string.Format("SELECT NEXT VALUE FOR {0}", sequenceName)).ToList();
            long nextVal = rawQuery.Single();

            return nextVal;
        }


        #endregion
    }
View Code

 

posted @ 2019-04-16 15:27  古兴越  阅读(432)  评论(0编辑  收藏  举报