其他分享
首页 > 其他分享> > EF批量操作数据之EntityFramework.Extended

EF批量操作数据之EntityFramework.Extended

作者:互联网

EF批量操作数据之EntityFramework.Extended

一、安装EntityFramework.Extended(环境为VS2019)

(1)

 

(2)

 

 

(3)

 

(4)

 

 安装成功

 

 

二 、使用实例

1.首先引用命名空间

    using EntityFramework.Extensions;

2.批量添加 数据 AddRange()发放,EF自带改方法

TestOne _context = new DBA.TestOne();
DateTime start = DateTime.Now;
for (int i = 0; i < 10000; i++)
{
    _context.Numeber1.Add(new Numeber1()
    {
        Num1 = i
    });
    _context.SaveChanges();
}
Console.WriteLine(_context.Numeber1.Count());
Console.WriteLine("总时长秒数:" + (DateTime.Now - start).TotalSeconds); //调试状态下 500多秒,非调试状态下 280秒

//批量新增
List<Numeber1> list = new List<Numeber1>();
for (int i = 0; i < 10000; i++)
{
    list.Add(new Numeber1()
    {
        Num1 = i
    });
}
_context.Numeber1.AddRange(list);
_context.SaveChanges();
Console.WriteLine("总时长秒数:" + (DateTime.Now - start).TotalSeconds); //批量添加9秒钟


3.批量更新 

//data为修改的行数
int   data =context.LogData.Where(a=>a.EntityKey=="aa").Update(b=> new LogData { EntityName = "ss" });
//第二种写法,这种是针对DbSet的,已经标注过时了
 var data = context.LogData.Update(a => a.EntityKey == "aa",b=> new LogData { EntityName = "ss" });
//批量更新
TestOne _context = new DBA.TestOne();
DateTime start = DateTime.Now;
int count = _context.Numeber1.Where(q => q.ID > 10000).Update(q => new Numeber1()
{
    Num1 = q.Num1 * 1000
});
_context.SaveChanges();
Console.WriteLine("总共更新数据:" + count);
Console.WriteLine("总时长秒数:" + (DateTime.Now - start).TotalSeconds); //批量更新:1秒多时间

4.批量 删除

//记得引用
using EntityFramework.Extensions;
//这两种写法都可以,Context是你的EF上下文对象.
context.LogData.Delete(a => a.EntityKey == "aa");
context.LogData.Where(a => a.EntityKey == "aa").Delete();
//批量删除操作
TestOne _context = new DBA.TestOne();
DateTime start = DateTime.Now;
int count = _context.Numeber1.Where(q => q.ID <= 30000).Delete();
_context.SaveChanges();
Console.WriteLine("总共删除数据:" + count);
Console.WriteLine("总时长秒数:" + (DateTime.Now - start).TotalSeconds); //批量删除:1秒左右时间


5.批量查询  

   var count =context.LogData.FutureCount();
                    var data = context.LogData.FutureFirstOrDefault(); 
                    var datalist = context.LogData.Future();
                    //在同一个代码上下文中,count,data,datalist这三个对象
                    //任意一个,第一次tolist或者.Value的时候,会连接一次数据库
                    //同时查询这三个数据,而不会分三次查询
                    var datalists = datalist.ToList();
                    int countdata = count.Value;  


6.查询缓存 

//使用默认的缓存时间
var tasks = db.Tasks
    .Where(t => t.CompleteDate == null)
    .FromCache();

//查询结果缓存300秒
var tasks = db.Tasks
    .Where(t => t.AssignedId == myUserId && t.CompleteDate == null)
    .FromCache(CachePolicy.WithDurationExpiration(TimeSpan.FromSeconds(300)));

标签:Extended,批量,EF,DateTime,EntityFramework,LogData,Numeber1,context,new
来源: https://blog.csdn.net/QYUANC/article/details/116947484