如何进行批量插入/更新(最佳性能)实体框架

时间:2014-05-05 23:49:13

标签: entity-framework entity-framework-6

我正在尝试更新/插入大约100条记录:

public static bool SaveTemplates(List<SecurityTemplateItemModel> templates)
        {

            try
            {
                using (SecurityDS service = new SecurityDS())
                {
                    foreach (var item in templates)
                    {
                        if (item.IsNew)
                        {
                            // insert
                            service.AddToSecurityTemplateExceptions(new SecurityTemplateException()
                            {
                                ObjectId = item.ObjectId,
                                AccessType = item.AccessType,
                                PlatformType = item.PlatformType,
                                TemplateUid = item.TemplateUid
                            });
                        }
                        else
                        {

                            // update
                            var exception = service.SecurityTemplateExceptions.Where(e => e.ObjectId == item.ObjectId && e.TemplateUid == item.TemplateUid).FirstOrDefault();
                            exception.AccessType = item.AccessType;
                            exception.PlatformType = item.PlatformType;

                            service.UpdateObject(exception);
                        }
                    }

                    service.SaveChanges();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

我正在使用数据服务,并且不知道性能问题是否来自那里。但是函数检查实体是否为new然后添加到集合中,如果没有,则获取Entity Framework实体并更新某个值,然后更新对象,最后保存更改。

此过程大约需要15秒,并且应该在1或2秒内完成。

有关如何做到这一点的任何线索?或者如果有更好的方法?

1 个答案:

答案 0 :(得分:0)

我只是从使用 DataServices 更改为 WCF服务公开POCO模型,它的效果非常好。