DbSet 在 EF7 中没有 Find 方法 [英] DbSet doesn't have a Find method in EF7
本文介绍了DbSet 在 EF7 中没有 Find 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个通用存储库来访问我的数据库.在 EF6 中,我能够这样做以获得特定实体:
I am trying to create a generic repository to access my database. In EF6 I was able to do that in order to get a specific entity:
protected IDbSet<T> dbset;
public T Get(object id)
{
return this.dbset.Find(id);
}
EF7 中的 DbSet 缺少 Find 方法.有没有办法实现上面这段代码?
DbSet in EF7 is missing a Find method. Is there a way to implement the above piece of code?
推荐答案
这里是作为扩展方法的 .Find()
的一个非常粗糙、不完整且未经测试的实现.如果不出意外,它应该能让你指明正确的方向.
Here's a very crude, incomplete, and untested implementation of .Find()
as an extension method. If nothing else, it should get you pointed in the right direction.
实际实现由 #797 跟踪.
static TEntity Find<TEntity>(this DbSet<TEntity> set, params object[] keyValues)
where TEntity : class
{
var context = ((IAccessor<IServiceProvider>)set).Service.GetService<DbContext>();
var entityType = context.Model.GetEntityType(typeof(TEntity));
var key = entityType.GetPrimaryKey();
var entries = context.ChangeTracker.Entries<TEntity>();
var i = 0;
foreach (var property in key.Properties)
{
var keyValue = keyValues[i];
entries = entries.Where(e => e.Property(property.Name).CurrentValue == keyValue);
i++;
}
var entry = entries.FirstOrDefault();
if (entry != null)
{
// Return the local object if it exists.
return entry.Entity;
}
// TODO: Build the real LINQ Expression
// set.Where(x => x.Id == keyValues[0]);
var parameter = Expression.Parameter(typeof(TEntity), "x");
var query = set.Where((Expression<Func<TEntity, bool>>)
Expression.Lambda(
Expression.Equal(
Expression.Property(parameter, "Id"),
Expression.Constant(keyValues[0])),
parameter));
// Look in the database
return query.FirstOrDefault();
}
这篇关于DbSet 在 EF7 中没有 Find 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文