Entity framework 如何批量插入/更新(最佳性能)实体框架
我正在尝试更新/插入大约100条记录:Entity framework 如何批量插入/更新(最佳性能)实体框架,entity-framework,entity-framework-6,Entity Framework,Entity Framework 6,我正在尝试更新/插入大约100条记录: public static bool SaveTemplates(List<SecurityTemplateItemModel> templates) { try { using (SecurityDS service = new SecurityDS()) { foreach
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;
}
}
我正在使用数据服务,不知道性能问题是否来自数据服务。但是函数检查实体是否是新的,然后添加到集合中,如果不是,则获取实体框架实体并更新一些值,然后更新对象并最终保存更改
这个过程大约需要15秒,应该在1到2秒内完成
你知道怎么做吗?或者如果有更好的方法?我只是从使用数据服务改为只使用WCF服务来公开POCO模型,效果非常好。您的SecurityDS是DbContext吗?是数据服务参考吗。但我认为几乎是一样的,只是中间的一层。我不喜欢的是,在每一个循环中,我都要检查实体是否有效,然后更新值。我认为这是很糟糕的性能,使用ADO.NET和存储过程可能会更好。从您的代码中,您只需检查bool属性,因此不会有性能问题,除非它是一个隐藏的get方法,下面有一个复杂的实现。放一些秒表,检查你的代码在哪里变慢,这可能会有所帮助。这可能是一个延迟加载问题。您从项关联的实体中获取的任何属性是否存在?尝试关闭函数的延迟加载。