c# - IDbSet 和 DbSet 有什么区别?

标签 c# entity-framework

有什么区别

public IDbSet<Chrip> Chirps { get; set; } 

public DbSet<Chrip> Chirps { get; set; }  

它们一样吗?

最佳答案

Sam I am's answer简洁地定义了接口(interface)和类之间的区别,但是在选择在代码中使用哪一个时还有其他注意事项。

具体来说 - 一个类可以实现多个接口(interface),或者可以实现任何接口(interface)未定义的方法和属性。

在这种情况下, IDbSet<TEntity> 接口(interface)定义了 DbSet<TEntity> 使用的大部分 方法和属性类,但不是全部。例如,FindAsync , RemoveRangeSqlQuery方法只存在于具体的类实现中。如果您在代码中使用该接口(interface),那么如果不首先转换为具体类型,您将无法使用这些特定方法。

此外,the Remarks section in the MSDN for IDbSet<TEntity> 还有一个有趣的地方:

IDbSet<TEntity> was originally intended to allow creation of test doubles (mocks or fakes) for DbSet<TEntity>. However, this approach has issues in that adding new members to an interface breaks existing code that already implements the interface without the new members. Therefore, starting with EF6, no new members will be added to this interface and it is recommended that DbSet<TEntity> be used as the base class for test doubles.

我相信可以安全地扩展这种思路,即您通常应该使用 DbSet<TEntity> 来声明您的属性。而不是 IDbSet<TEntity>除非你有充分的理由不这样做。

关于c# - IDbSet 和 DbSet 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38443037/

相关文章:

c# - 如何判断.Net 标准库是否支持一个类?

c# - 如何在ListView中插入超链接

c# - EF 代码优先 : Cannot connect to SQL Server

c# - 使用 Entity Framework 6 创建计算字段

entity-framework - Entity Framework 嵌套投影很慢

c# - 使用 WiX 工具集编辑文件

c# - 使用 openssl 在 iPhone 上正确获取 HMACSHA1

c# - Validation.ErrorTemplate 确实在绑定(bind)到对象属性时触发

c# - 在 PostgreSQL 中使用特定模式的 Linq 和实体迁移

c# - 如何在 Entity Framework 中使用主键查找数据?