[英]C# MVC ASP.NET Most Efficient way to get data from database with id
I'm new to MVC and databases, but I'm fairly certain the way that I'm getting data from the database is incredibly inefficient. 我是MVC和数据库的新手,但我可以肯定地说,从数据库获取数据的方式效率极低。
public class PokemonViewController : Controller
{
private PokemonDayCareDBEntities1 db = new PokemonDayCareDBEntities1();
[Authorize]
public ActionResult Pokemon(int id)
{
var pkmn = db.PlayerPkmns.ToList();
PlayerPkmn thispkmn = null;
//get pokemon from database where id = id
foreach (var item in pkmn)
{
if (item.Id == id)
{
thispkmn = item;
}
}
....
I have the unique ID of the Pokemon that resides in the PlayerPkmns table, but I'm looping through the entire table in order to find the matching ID. 我具有位于PlayerPkmns表中的Pokemon的唯一ID,但是我在整个表中循环查找以找到匹配的ID。
Depending on how large the table, the time this takes to execute would increase. 根据表的大小,执行所需的时间会增加。
I'm positive there's a better way - would anyone know if there is one (also, the syntax on how to use it) 我很肯定有更好的方法-谁知道是否有一种方法(以及有关如何使用它的语法)
Thanks! 谢谢!
SingleOrDefault
is your friend here. SingleOrDefault
是您的朋友在这里。
Change this: 更改此:
var pkmn = db.PlayerPkmns.ToList();
To 至
var pkmn = db.PlayerPkmns.SingleOrDefault(x => x.Id == id);
This will translate (roughly) into the following SQL 这将(大致)转换为以下SQL
SELECT TOP 1 * FROM PlayerPkmns WHERE ID = @id
检索实体的最有效方法是使用.Find(),其中primaryKey是您要传入的ID。
var PlayerPkmn= db.PlayerPkmns.Find(primaryKey)
As you are using Linq to Entities, you should be able to use the Where()
in combination with FirstOrDefault()
: 在使用Linq to Entities时,应该可以将
Where()
与FirstOrDefault()
结合使用:
var pkmn = db.PlayerPkmns.Where(x=>x.Id == id).FirstOrDefault();
The way you are doing right now will cause all the records to be brought in memory which is not what you want i believe, and it will be much performant than the way you are doing right now, as with the way you are doing, it will load all records in to the memory. 您现在的工作方式将导致所有记录都被存储到内存中,这不是我想要的,并且它的性能将比您现在的工作方式(以及您所做的方式)好得多将所有记录加载到内存中。
I suppose that PokemonDayCareDBEntities1
is an Entity Framework Data Context . 我想
PokemonDayCareDBEntities1
是一个实体框架数据上下文 。 In that case you can use db.PlayerPkmns.Find(id)
or db.PlayerPkmns.SingleOrDefault(x => x.Id == id)
if you want to handle the case where the entity does not exist in the DB, db.PlayerPkmns.Single(x => x.Id == id)
if you are sure that there is strictly one element in the DB (will throw if the entity does not exist). 在这种情况下,如果要处理实体在数据库
db.PlayerPkmns.Single(x => x.Id == id)
中不存在的情况,则可以使用db.PlayerPkmns.Find(id)
或db.PlayerPkmns.SingleOrDefault(x => x.Id == id)
db.PlayerPkmns.Single(x => x.Id == id)
如果您确定数据库中严格存在一个元素(如果该实体不存在,则会抛出该元素)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.