Sasan Bazade
Sasan Bazade

Reputation: 131

What is the difference between IDbSet and DbSet?

What is the difference between

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

and

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

Are they the same?

Upvotes: 11

Views: 8298

Answers (3)

sergiokml
sergiokml

Reputation: 121

They refer to different namespaces. One is for EF Core and the other is not recommended.

Microsoft.EntityFrameworkCore.DbSet<T>
System.Data.Entity.IDbSet<T>

Upvotes: 0

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241890

Sam I am's answer neatly defines the difference between an interface and a class, but there are additional considerations when choosing which to use in your code.

Specifically - a class can implement more than one interface, or can implement methods and properties not defined by any interface.

In this case, the IDbSet<TEntity> interface defines most of the methods and properties used by the DbSet<TEntity> class, but not all of them. For example, the FindAsync, RemoveRange and SqlQuery methods only exist on the concrete class implementation. If you use the interface in your code, you won't have those particular methods available without first casting to the concrete type.

Also, the Remarks section in the MSDN for IDbSet<TEntity> has another interesting point:

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.

I believe it it safe to extend that line of thinking to say that you should usually declare your properties using DbSet<TEntity> instead of IDbSet<TEntity> unless you have a good reason not to.

Upvotes: 21

Usually, when a type name begins with an I it is an interface. This is not a hard rule, but just a naming convention.

DbSet probably implements IDbSet


Suppose you have an interface like this

public interface IFoo
{
    int Echo(int bar);
}

A class would implement an interface like this

public class Foo : IFoo
{
    public int Echo(int bar)
    {
        return bar;
    }
}

What this means is that your class Foo must implement every method the interface says it does, which in this case is a method named Echo which takes an int as input, and returns an int.

What this allows you to do is to is to treat a bunch of different classes the same way, even if you don't know how they're implemented. For more information, see Polymorphism.

Upvotes: 2

Related Questions