Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 229
Sasan Bazade Avatar asked Jul 18 '16 17:07

Sasan Bazade


2 Answers

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.

like image 160
Matt Johnson-Pint Avatar answered Nov 13 '22 19:11

Matt Johnson-Pint


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.

like image 34
Sam I am says Reinstate Monica Avatar answered Nov 13 '22 17:11

Sam I am says Reinstate Monica