gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:07:59 26 4
gpt4 key购买 nike

有什么区别

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com