gpt4 book ai didi

c# - Entity Framework 不将更改保存到数据库中

转载 作者:可可西里 更新时间:2023-11-01 07:43:55 26 4
gpt4 key购买 nike

我很困惑为什么这段代码不起作用,它应该在循环后将更改保存到数据库但是当我将 SaveChanges 方法放在循环中时,它会将记录保存到数据库中但在外面它不保存任何东西?大概只有300~1000条记录

    static bool lisReady = false;
static bool sacclReady = false;

static void Main(string[] args)
{
Logger("Starting services");
ConnectDBLis().Wait();
ConnectDBSaccl().Wait();
Thread.Sleep(1000);
if (lisReady & sacclReady){
//start
Logger("Services ready");
StartExport().Wait();
}
}

static async Task<bool> StartExport()
{
lis lisdb = new lis();
nrlsaccl saccldb = new nrlsaccl();
var getTestOrders = await lisdb.test_orders.ToListAsync();
Logger("Services starting");
foreach (var tO in getTestOrders.Where(x => x.entry_datetime.Value.Year == 2016))
{
foreach (var tr in tO.test_results)
{
foreach (var tL in tr.test_result_logs)
{
results_availability postResults = new results_availability
{
first_name = tO.patient_orders.patient.first_name,
middle_name = tO.patient_orders.patient.middle_name,
last_name = tO.patient_orders.patient.last_name,
birthdate = tO.patient_orders.patient.birthdate,
};
if (postResults.id == 0)
{
saccldb.results_availability.Add(postResults);
}
else
{
saccldb.Entry(postResults).State = EntityState.Modified;
}
}
}
}
await saccldb.SaveChangesAsync();
return true;
}

编辑:

所以我将记录限制为 100 条并且保存更改有效,即时 3000 条记录不起作用,有什么解决方案吗?

最佳答案

这段代码并不能完全解决你的问题,这是对你的问题的一些考虑。

注意:添加 1200 条记录和 300 条修改时这对我有用

 static async Task<bool> StartExport()
{
using (var db = new Entities())
{
var appraisals = await db.Appraisals.ToListAsync();

db.Database.CommandTimeout = 300;
//Disabling auto detect changes enabled will bring some performance tweaks
db.Configuration.AutoDetectChangesEnabled = false;
foreach (var appraisal in appraisals.Where(g => g.Id > 1))
{

if (appraisal.Id == 10)
{
appraisal.AppraisalName = "New name";
db.Entry(appraisal).State = EntityState.Added;
}
else
{
appraisal.AppraisalName = "Modified name";
db.Entry(appraisal).State = EntityState.Modified;
}
}

db.Configuration.AutoDetectChangesEnabled = true;

if (await db.SaveChangesAsync() > 1)
return true;
else
return false;
}
}

You could use db.Database.CommandTimeout = 300; to increase the timeout of you connection.

Entity framework 6 provides AddRange() This will insert the items in one shot, it will disable AutoDetectChangesEnabled and insert the entities

在您的情况下,您不想将实体标记为已修改,EF 已经很好地跟踪了它。 Entity Framework - Why explicitly set entity state to modified?

The purpose of change tracking to find that you have changed a value on attached entity and put it to modified state. Setting state manually is important in case of detached entities (entities loaded without change tracking or created outside of the current context).

这里我们将所有实体附加到上下文本身

关于c# - Entity Framework 不将更改保存到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36707696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com