您更喜欢 EF 4 中的 ObjectSet 和 CreateQuery 哪一个?
我一直在下面编码。但我找到了另一种方法第二部分。哪一个比另一个更优选。有什么区别?哪一个的性能比其他的更好?
public T Single(Func<T, bool> predicate)
{
return _context.CreateQuery<T>("[" + typeof(T).Name + "]").Where(predicate).Single();
}
另一种用法
public T Single(Func<T, bool> predicate)
{
return _objectSet.Single<T>(predicate);
}
哪种用法更受青睐?
i have been coding below. But i find another method secand part . which one is more preferable than other. what is the differece? whic one has more performance than other?
public T Single(Func<T, bool> predicate)
{
return _context.CreateQuery<T>("[" + typeof(T).Name + "]").Where(predicate).Single();
}
ANOTHER USAGE
public T Single(Func<T, bool> predicate)
{
return _objectSet.Single<T>(predicate);
}
which one is more prefer than other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它们是完全不同的事物,具有完全不同的目的。
ObjectSet
是一个强类型属性,允许您针对概念模型运行LINQ查询。 (ctx.Apples.Where(x => x.Color == "Red")
)。CreateQuery
是一种允许您针对物理模型运行本机 SQL 的方法。也称为EntitySQL。 (SELECT * FROM dbo.Apples WHERE Color = "Red"
)ObjectSet
更加类型安全,因为模型上的实体作为 ObjectSet 上的属性公开,它是通过泛型键入的。另一方面,CreateQuery
也输入到实体,但实际查询是 EntitySQL,一个字符串参数 - 意味着可能由于拼写错误而发生运行时错误。使用ObjectSet
遇到的唯一运行时错误是 CLR 特定错误(空引用等)或 SQL 特定错误(外键约束、PK 冲突等)。正如@adrift 还提到的,
IObjectSet
是可模拟的,但是当然您可以为CreateQuery
创建一个代理/包装类并模拟它。过去几个月我一直在使用 Entity Framework 4.0,但没有发现
CreateQuery
的任何用法。我要么使用ObjectSet
要么使用存储过程。They are completely different things, with completely different purposes.
ObjectSet<T>
is a strongly-typed property which allows you to run LINQ queries against the conceptual model. (ctx.Apples.Where(x => x.Color == "Red")
).CreateQuery<T>
is a method which allows you to run native SQL against the physical model. Also known as EntitySQL. (SELECT * FROM dbo.Apples WHERE Color = "Red"
)ObjectSet<T>
is more type-safe, because entities on the model are exposed as properties on the ObjectSet, which is typed via generics.CreateQuery<T>
on the other hand is also typed to the entity, but the actual query is EntitySQL, a string parameter - meaning possible runtime errors can occur because of typos. The only runtime errors you will get withObjectSet<T>
is CLR specific errors (null references, etc) or SQL specific errors (foreign key constraint, PK violation, etc).As @adrift also mentions,
IObjectSet<T>
is mockable, however of course you could create a proxy/wrapper class forCreateQuery<T>
and mock that.I have used Entity Framework 4.0 for the past few months and have not found a single usage for
CreateQuery<T>
. I either useObjectSet<T>
or Stored Procedures.我更喜欢使用
IObjectSet
因为您可以创建一个实现IObjectSet
的假冒单元测试。有关此问题的讨论,请参阅 此主题 和这篇文章。I would prefer using
IObjectSet
since you can create a fake that implementsIObjectSet<TEntity>
for unit testing. For a discussion of this, see this thread and this post.