我正在寻找一种通用的方法来检查一个实体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);
}
Run Code Online (Sandbox Code Playgroud)
该行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 …
Run Code Online (Sandbox Code Playgroud)