[英]Entity Framework : ExecuteStoreQuery not found in ObjectContext
[英]Entity Framework: ObjectContext.ExecuteStoreQuery produces detached objects
我需要运行一些自定义SQL来从表中返回对象列表。 我为此使用ExecuteStoreQuery。
var q = context.ExecuteStoreQuery<ProductionUnit>(MySelectString, new SqlParameter("@ProductionUnitId", value));
这确实导致q包含ObjectResult集合,但是实际的ProductionUnit元素已分离并且其EntityKey为null。 尝试处理其中一些对象或其关系时,这会产生许多问题。 我的SQL查询返回的结果集包含相应ProductionUnits表的所有列(仅此而已)。
为了跟踪这些对象,我还需要做其他事情吗?或者这是设计使然?
我自己解决了这个问题-您需要使用ExecuteStoreQuery重载,该重载允许您为返回的实体指定EntitySet名称。
由于似乎没有可接受的代码答案...
如@neaorin所说,要确保跟踪对返回实体的更改,请使用方法
ExecuteStoreQuery <..>(commandText,entitySetName,MergeOptions,args参数)
如下:
string strQuery = "SELECT * FROM employees WHERE id=999";
List<employee> employees;
services = context.ExecuteStoreQuery<employee>(strQuery, "employees", System.Data.Objects.MergeOption.AppendOnly).ToList();
MergeOptions参数指示如果这些返回的实体中的某些已经在上下文中浮动,那么框架将执行什么操作,即是覆盖它们还是使用现有对象(默认值)。
在我的情况下,解决方案是使用EntitySet字符串和MergeOption的重载,如先前答案中所述。 但是,ExecuteStoreQuery仍返回EntityKey = null且EntityState = Detached的实体项目。
原因是我使用的EntitySet字符串是错误的,我通过使用以下命令获得了正确的EntitySet字符串:
var records = _entities.ExecuteStoreQuery<ProductionUnit>(query, typeof(ProductionUnit).Name, System.Data.Entity.Core.Objects.MergeOption.AppendOnly).ToList();
我通过使用typeof(ProductionUnit).Name
获得了正确的EntitySet字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.