【发布时间】:2011-08-26 11:57:14
【问题描述】:
类似于Best way to check if object exists in Entity Framework?
我正在寻找一种通用方法来检查 DbSet 中的实体。像这样的东西,这是行不通的:
private DbContext DbContext { get; set; }
private DbSet<T> DbSet { get; set; }
public Boolean Exists(T entity) {
return ((from item in this.DbSet
where item == entity
select item).Count() > 0);
}
where item == entity 行适用于 LINQ to SQL,但显然不适用于 LINQ to Entities。由于实体可能有不同的键,我不能让它们都继承自具有已知键的通用抽象以进行比较。
我可以这样做,但我担心捕获异常作为验证过程的性能这也不起作用,因为只要实体被分离,OriginalValues 属性就可以'无法获得:
public Boolean Exists(T entity) {
try {
var current = this.DbContext.Entry(entity).OriginalValues;
// Won't reach this line if the entity isn't in the database yet
return true;
}
catch (Exception ex) {
return false;
}
}
【问题讨论】:
-
为了澄清想要一个通用的
Exists()方法的原因,我希望能够创建一个Save()方法,它可以确定是否需要将实体添加到上下文中(@ 987654329@) 或附件 (UPDATE)。我没有在问题中提到这一点,因为一旦我有了Exists(),Save()就变得微不足道了。
标签: c# generics entity-framework-4.1