如何使用DBContext在EF中优化CRUD操作?

时间:2019-09-05 18:41:14

标签: c# sql-server entity-framework asp.net-core

我有一个从API抓取数据并将其存储到数据库中的函数。

public async Task GetApps()
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "apps?per_page=200");
            var response = await _client_SB.SendAsync(request);
            var json = await response.Content.ReadAsStringAsync();
            AppsClass.AppsRootobject model = JsonConvert.DeserializeObject<AppsClass.AppsRootobject>(json);
            using (var scope = _scopeFactory.CreateScope())
            {
                var _DBcontext = scope.ServiceProvider.GetRequiredService<PCFStatusContexts>();

                foreach (var item in model.resources)
                {
                    var g = Guid.Parse(item.guid);
                    var x = _DBcontext.Apps.FirstOrDefault(o => o.AppGuid == g);

                    if (x == null)
                    {
                        _DBcontext.Apps.Add(new Apps
                        {
                            AppGuid = Guid.Parse(item.guid),
                            Name = item.name,
                            State = item.state,
                            CreatedAt = item.created_at,
                            UpdatedAt = item.updated_at,
                            SpaceGuid = Guid.Parse(item.relationships.space.data.guid),
                            Foundation = 2,
                            Timestamp = DateTime.Now
                        });
                    }

                    else if (x.UpdatedAt != item.updated_at)
                    {
                        x.State = item.state;
                        x.CreatedAt = item.created_at;
                        x.UpdatedAt = item.updated_at;
                        x.Timestamp = DateTime.Now;
                    }

                    var guids = model.resources.Select(r => Guid.Parse(r.guid));
                    var apps = _DBcontext.Apps.Where(o => guids.Contains(o.AppGuid) == false && o.Foundation == 2);
                    foreach (var app in apps)
                    {
                        app.DeletedAt = DateTime.Now;
                    }
                }

                await _DBcontext.SaveChangesAsync();
            }
        }

除了DeletedAt的代码段

以外,上面的函数可以正常工作
var guids = model.resources.Select(r => Guid.Parse(r.guid));
                    var apps = _DBcontext.Apps.Where(o => guids.Contains(o.AppGuid) == false && o.Foundation == 2);
                    foreach (var app in apps)
                    {
                        app.DeletedAt = DateTime.Now;
                    }

这并不是说它根本无法工作,但是当GetApps函数由于该代码片段而每秒调用一次时,我得到了以下错误消息

  

遍历查询的结果时发生异常   上下文类型为“ TestApp.Context.DBContexts”。         System.InvalidOperationException:超时已过期。从池中获取连接之前已经过超时时间。这个   可能是因为所有池化连接都在使用中并且最大   池达到了大小。

如果我删除了DeletedAt片段,那很好,但是我需要该功能,有什么方法可以优化它吗?我可以使其异步吗?

0 个答案:

没有答案