是否有理由从FindAsync()
接口(interface)中省略IDbSet<T>
方法? Find
是接口(interface)的一部分,异步版本似乎不可用似乎很奇怪。我需要转换为DbSet<T>
才能访问它,这有点麻烦:
User user = await ((DbSet<User>)db.Users)
.FindAsync("de7d5d4a-9d0f-48ff-9478-d240cd5eb035");
最佳答案
如果您拥有IDbSet<T>
的使用者,而我假设您这样做是因为想要从使用者中访问FindAsync()
,那么一个简单的解决方案是创建自己的接口(interface),该接口(interface)包含IDbSet并包含要使用的任何FindAsync()
方法:
public interface IAsyncDbSet<T> : IDbSet<T>
where T : class
{
Task<T> FindAsync(params Object[] keyValues);
}
这解决了不必强制转换为DbSet的问题-顺便说一句,它吹散了契约编码的抽象性好处。但这也带来了自己的一系列问题。
更好的解决方案(imo)需要做更多的工作,是定义一个仅包含要在DbSet对象中使用的成员的接口(interface),在实现该接口(interface)时子类化DbSet,然后在代码中使用该接口(interface):
public interface IMyAsyncDbSet<TEntity>
where TEntity : class
{
TEntity Add(TEntity entity);
TEntity Remove(TEntity entity);
// Copy other methods from IDbSet<T> as needed.
Task<Object> FindAsync(params Object[] keyValues);
}
public class MyDbSet<T> : DbSet<T>, IMyAsyncDbSet<T>
where T : class
{
}
确实,这是一个适配器模式。它将代码期望的接口(interface)与Entity Framework提供的接口(interface)分离。现在,它们是相同的-这就是为什么该实现除了继承
DbSet<T>
之外什么也不做的原因。但是后来它们可能会分歧。到那时,您仍然可以使用最新的DbSet而不会破坏您的代码。关于c# - IDbSet <T>上没有FindAsync()方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21800967/