通过实体框架中的关键字查找实体 [英] Finding entities by key in entity framework

查看:82
本文介绍了通过实体框架中的关键字查找实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在做

  context.Single(x => x.Id == id); 

完全一样

  context.Find(new [] {id}); 

在实体框架中

解决方案

不。 查找首先检查对象是否已经加载到上下文中。如果是,则返回此对象。如果没有它从数据库查询实体。 单个始终从数据库查询对象。

p>另外查找返回 null 如果该对象既不在上下文中也不在数据库中。 Single 如果在数据库中找不到,则抛出异常。



您的意思是: context.SomeEntitySet.Find(id) context.SomeEntitySet.Single(x => x.Id == id),我猜。


Is doing

context.Single(x => x.Id == id);

exactly the same as

context.Find(new[] { id });

in the entity framework?

解决方案

No. Find checks first if the object is already loaded into the context. If yes it just returns this object. If no it queries the entity from the database. Single always queries the object from the database. If it is already in the context it gets updated with the values from the DB. (Edit: The last sentence is wrong, see comments!)

Also Find returns null if the object is neither in the context nor in the database. Single throws an exception if it isn't found in the database.

You mean: context.SomeEntitySet.Find(id) and context.SomeEntitySet.Single(x => x.Id == id), I guess.

这篇关于通过实体框架中的关键字查找实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆