简体   繁体   English

如何优化此实体框架代码

[英]How to optimize this entity framework code

I'm fetching movie meta data from and API and adding them to database using entity framework using the following code 我正在使用和从实体API获取电影元数据,并使用以下代码使用实体框架将其添加到数据库中

This code this taking upto 20% CPU when called for one movie. 调用一部电影时,此代码最多占用20%的CPU。 I'm using one context for one insert. 我将一个上下文用于一个插入。 Add() and DBSet.Local.Where(..) methods are the most expensive here. Add()和DBSet.Local.Where(..)方法在这里最昂贵。 How can I optimize the code to reduce CPU. 如何优化代码以减少CPU。

Update: On code profiling I found DBSet.Local.Where(..) is where the CPU is eating up. 更新:在代码分析中,我发现DBSet.Local.Where(..)是CPU耗尽的地方。 My reason to call DBSet.Local.Where is to find out if I've already added that object (person) so that I don't re-add it. 我之所以要调用DBSet.Local.Where的原因是要确定我是否已经添加了该对象(人),以便不重新添加它。 Thoughts? 有什么想法吗?

This Movies.Where(My => My.ID == Movie.Id).FirstOrDefault() can be optimize by calling Movies.Find(Movie.Id) . 可以通过调用Movies.Find(Movie.Id)来优化此Movies.Where(My => My.ID == Movie.Id).FirstOrDefault() Movies.Find(Movie.Id)

Finds an entity with the given primary key values. 查找具有给定主键值的实体。 If an entity with the given primary key values exists in the context, then it is returned immediately without making a request to the store. 如果上下文中存在具有给定主键值的实体,则将立即返回该实体,而无需向商店提出请求。 https://msdn.microsoft.com/en-us/library/gg696418(v=vs.113).aspx https://msdn.microsoft.com/zh-CN/library/gg696418(v=vs.113).aspx

I don't see any optimizations for the Add() 我没有看到对Add()任何优化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM