Difference between DbSet property and Set() function in EF Core?












2















Given this kind of context:



public class FooContext : DbContext 
{
public FooContext(DbContextOptions<FooContext> opts) : base(opts)
{ }

public DbSet<Bar> Bars { get; set; }
}


I can get to a Bar in two ways:



fooContext.Bars.Add(new Bar()); // Approach 1


or



fooContext.Set<Bar>().Add(new Bar()); // Approach 2


What is the difference between the two approaches?



I've tried to answer my own question by:




  • Inspecting the intellisense for both (only tells me that Set<T>() also creates a DbSet<T>)


  • Googling for "EF Core Set vs property" but that doesn't seem to be the 'right' query


  • Google for DbSet<T> specifically on the docs urls but no relevant results here either it seems

  • Reading the intro of the DbSet<T> docs which just suggests that you can get a set through either of the two methods (not if there is or isn't a difference)

  • Read the Set<T>() docs which has no relevant info


But I could not find any good explanation about which of the two is used for which purpose. What is the difference? Or perhaps more importantly: where and how should I be able to find this in the docs?










share|improve this question


















  • 1





    They appear to do the same thing: github.com/aspnet/EntityFrameworkCore/blob/master/src/EFCore/… Line 245. The difference I think is that Set<Bar> will use IDbSetSource to lookup the type at runtime and work out what table it requires, whereas Bar property does this at compile time.

    – Ben
    Nov 25 '18 at 17:20











  • @Ben Ahh yes of course. Several years down the road and I still need the occassional reminder that Microsoft open sources just about anything in this space. Thanks!

    – Jeroen
    Nov 25 '18 at 17:50
















2















Given this kind of context:



public class FooContext : DbContext 
{
public FooContext(DbContextOptions<FooContext> opts) : base(opts)
{ }

public DbSet<Bar> Bars { get; set; }
}


I can get to a Bar in two ways:



fooContext.Bars.Add(new Bar()); // Approach 1


or



fooContext.Set<Bar>().Add(new Bar()); // Approach 2


What is the difference between the two approaches?



I've tried to answer my own question by:




  • Inspecting the intellisense for both (only tells me that Set<T>() also creates a DbSet<T>)


  • Googling for "EF Core Set vs property" but that doesn't seem to be the 'right' query


  • Google for DbSet<T> specifically on the docs urls but no relevant results here either it seems

  • Reading the intro of the DbSet<T> docs which just suggests that you can get a set through either of the two methods (not if there is or isn't a difference)

  • Read the Set<T>() docs which has no relevant info


But I could not find any good explanation about which of the two is used for which purpose. What is the difference? Or perhaps more importantly: where and how should I be able to find this in the docs?










share|improve this question


















  • 1





    They appear to do the same thing: github.com/aspnet/EntityFrameworkCore/blob/master/src/EFCore/… Line 245. The difference I think is that Set<Bar> will use IDbSetSource to lookup the type at runtime and work out what table it requires, whereas Bar property does this at compile time.

    – Ben
    Nov 25 '18 at 17:20











  • @Ben Ahh yes of course. Several years down the road and I still need the occassional reminder that Microsoft open sources just about anything in this space. Thanks!

    – Jeroen
    Nov 25 '18 at 17:50














2












2








2


2






Given this kind of context:



public class FooContext : DbContext 
{
public FooContext(DbContextOptions<FooContext> opts) : base(opts)
{ }

public DbSet<Bar> Bars { get; set; }
}


I can get to a Bar in two ways:



fooContext.Bars.Add(new Bar()); // Approach 1


or



fooContext.Set<Bar>().Add(new Bar()); // Approach 2


What is the difference between the two approaches?



I've tried to answer my own question by:




  • Inspecting the intellisense for both (only tells me that Set<T>() also creates a DbSet<T>)


  • Googling for "EF Core Set vs property" but that doesn't seem to be the 'right' query


  • Google for DbSet<T> specifically on the docs urls but no relevant results here either it seems

  • Reading the intro of the DbSet<T> docs which just suggests that you can get a set through either of the two methods (not if there is or isn't a difference)

  • Read the Set<T>() docs which has no relevant info


But I could not find any good explanation about which of the two is used for which purpose. What is the difference? Or perhaps more importantly: where and how should I be able to find this in the docs?










share|improve this question














Given this kind of context:



public class FooContext : DbContext 
{
public FooContext(DbContextOptions<FooContext> opts) : base(opts)
{ }

public DbSet<Bar> Bars { get; set; }
}


I can get to a Bar in two ways:



fooContext.Bars.Add(new Bar()); // Approach 1


or



fooContext.Set<Bar>().Add(new Bar()); // Approach 2


What is the difference between the two approaches?



I've tried to answer my own question by:




  • Inspecting the intellisense for both (only tells me that Set<T>() also creates a DbSet<T>)


  • Googling for "EF Core Set vs property" but that doesn't seem to be the 'right' query


  • Google for DbSet<T> specifically on the docs urls but no relevant results here either it seems

  • Reading the intro of the DbSet<T> docs which just suggests that you can get a set through either of the two methods (not if there is or isn't a difference)

  • Read the Set<T>() docs which has no relevant info


But I could not find any good explanation about which of the two is used for which purpose. What is the difference? Or perhaps more importantly: where and how should I be able to find this in the docs?







c# entity-framework-core






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 25 '18 at 16:26









JeroenJeroen

36.5k24129209




36.5k24129209








  • 1





    They appear to do the same thing: github.com/aspnet/EntityFrameworkCore/blob/master/src/EFCore/… Line 245. The difference I think is that Set<Bar> will use IDbSetSource to lookup the type at runtime and work out what table it requires, whereas Bar property does this at compile time.

    – Ben
    Nov 25 '18 at 17:20











  • @Ben Ahh yes of course. Several years down the road and I still need the occassional reminder that Microsoft open sources just about anything in this space. Thanks!

    – Jeroen
    Nov 25 '18 at 17:50














  • 1





    They appear to do the same thing: github.com/aspnet/EntityFrameworkCore/blob/master/src/EFCore/… Line 245. The difference I think is that Set<Bar> will use IDbSetSource to lookup the type at runtime and work out what table it requires, whereas Bar property does this at compile time.

    – Ben
    Nov 25 '18 at 17:20











  • @Ben Ahh yes of course. Several years down the road and I still need the occassional reminder that Microsoft open sources just about anything in this space. Thanks!

    – Jeroen
    Nov 25 '18 at 17:50








1




1





They appear to do the same thing: github.com/aspnet/EntityFrameworkCore/blob/master/src/EFCore/… Line 245. The difference I think is that Set<Bar> will use IDbSetSource to lookup the type at runtime and work out what table it requires, whereas Bar property does this at compile time.

– Ben
Nov 25 '18 at 17:20





They appear to do the same thing: github.com/aspnet/EntityFrameworkCore/blob/master/src/EFCore/… Line 245. The difference I think is that Set<Bar> will use IDbSetSource to lookup the type at runtime and work out what table it requires, whereas Bar property does this at compile time.

– Ben
Nov 25 '18 at 17:20













@Ben Ahh yes of course. Several years down the road and I still need the occassional reminder that Microsoft open sources just about anything in this space. Thanks!

– Jeroen
Nov 25 '18 at 17:50





@Ben Ahh yes of course. Several years down the road and I still need the occassional reminder that Microsoft open sources just about anything in this space. Thanks!

– Jeroen
Nov 25 '18 at 17:50












3 Answers
3






active

oldest

votes


















3














They do exactly the same thing. The real question is when will you use one over the other.



You use DbSet when you know the type of entity you want to play with. You simple write the DbContext name then the entity type name and you can create, read, update or delete entries for this entity with the entity methods available. You know what you want and you know where to do it.



You use Set when you don't know the entity type you want to play with. Lets say, you wanted to build a class that does your repository functions for creating, reading, updating and deleting entries for an entity. You want this class to be reusable so that you can just pass a DbContext on it and it will use the same create, read, update and delete methods. You don't know for sure what DbContext it will be used on or what DbSet the DbContext will have. Here's when you use generics so that your class can be used by any DbContext for any DbSet.



Here's an example of a class you can use for creating any entity on any DbSet in any DbContext



public class Repository<TDbContext> where TDbContext : DbContext
{
private TDbContext _context { get; }

public Repository(TDbContext context)
{
_context = context;
}

public TEntity Create<TEntity>(TEntity entity) where TEntity : class
{
if(entity != null)
{
var dataSet = _context.Set<TEntity>();

if(entity is IEnumerable)
{
dataSet.AddRange(entity);
}
else
{
dataSet.Add(entity);
}

_context.SaveChanges();


}

return entity;
}
}


And this is how to use it.



var dbContext01 = new DbContext01();
var dbContext02 = new DbContext02();

var repository01 = new Repository<DbContext01>(dbContext01);
var repository02 = new Repository<DbContext02>(dbContext02);

repository01.Create(new EntityOnDbContext01 {
Property01A = "String",
Property01B = "String"
});

repository02.Create(new EntityOnDbContext02 {
Property02A = 12345,
Property02B = 12345
});


Here's a link if you want to know more about generics. Its super awesome.



https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/






share|improve this answer































    2














    Unfortunately currently you won't find explanation in the official documentation, mainly because all these are functionally equivalent.



    First, the generic methods of DbConext like Add<TEntity>, Remove<TEntity>, Attach<TEntity> etc. a fully equivalent of the corresponding DbSet<TEntity> methods (actually currently they are the implementation of the later, i.e. DbSet methods simply call the corresponding DbContext generic method). Which one you use is just a matter of taste.



    Second, DbSet<TEntity> property and Set<TEntity> method are functionally equivalent, but do have some non functional differences.



    The DbSet properties are populated once at the context creation, while Set method always performs a lookup, so DbSet property access should be faster than Set method (although not significant).



    The important difference is actually the EF Core Including & Excluding Types convention:




    By convention, types that are exposed in DbSet properties on your context are included in your model. In addition, types that are mentioned in the OnModelCreating method are also included.




    So while you can keep your DbContext without exposed DbSet properties and work just with Set method, if you do so you have to tell explicitly EF Core which are your entity types by adding in OnModelCreating a call to modelBuilder.Entity<TEntity>(); for each entity type (this is what the documentation does mean by types that are mentioned in the OnModelCreating method).






    share|improve this answer































      0














      They are the same and actually returns the same DbSet instance.



      var options = //...;

      using (var ctx = new FooContext(options))
      {
      // true
      bool isSame = ReferenceEquals(ctx.Bars, ctx.Set<Bar>());
      }


      One use case for not including a DbSet property in your DbContext is when you want to hide an entity type from a consumer. (e.g. an entity that acts as join table for many-to-many relationship). You can then mark the entity as internal class so consumers also can't also access it using Set<>.



      Also, if you don't expose a DbSet property, you need to explicitly configure the entity or you'll get the following exception:



      //throws System.InvalidOperationException: 'The entity type 'Foo' was not found. Ensure that the entity type has been added to the model.'
      ctx.Set<Foo>().Add(new Foo());





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53469498%2fdifference-between-dbsett-property-and-sett-function-in-ef-core%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        3














        They do exactly the same thing. The real question is when will you use one over the other.



        You use DbSet when you know the type of entity you want to play with. You simple write the DbContext name then the entity type name and you can create, read, update or delete entries for this entity with the entity methods available. You know what you want and you know where to do it.



        You use Set when you don't know the entity type you want to play with. Lets say, you wanted to build a class that does your repository functions for creating, reading, updating and deleting entries for an entity. You want this class to be reusable so that you can just pass a DbContext on it and it will use the same create, read, update and delete methods. You don't know for sure what DbContext it will be used on or what DbSet the DbContext will have. Here's when you use generics so that your class can be used by any DbContext for any DbSet.



        Here's an example of a class you can use for creating any entity on any DbSet in any DbContext



        public class Repository<TDbContext> where TDbContext : DbContext
        {
        private TDbContext _context { get; }

        public Repository(TDbContext context)
        {
        _context = context;
        }

        public TEntity Create<TEntity>(TEntity entity) where TEntity : class
        {
        if(entity != null)
        {
        var dataSet = _context.Set<TEntity>();

        if(entity is IEnumerable)
        {
        dataSet.AddRange(entity);
        }
        else
        {
        dataSet.Add(entity);
        }

        _context.SaveChanges();


        }

        return entity;
        }
        }


        And this is how to use it.



        var dbContext01 = new DbContext01();
        var dbContext02 = new DbContext02();

        var repository01 = new Repository<DbContext01>(dbContext01);
        var repository02 = new Repository<DbContext02>(dbContext02);

        repository01.Create(new EntityOnDbContext01 {
        Property01A = "String",
        Property01B = "String"
        });

        repository02.Create(new EntityOnDbContext02 {
        Property02A = 12345,
        Property02B = 12345
        });


        Here's a link if you want to know more about generics. Its super awesome.



        https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/






        share|improve this answer




























          3














          They do exactly the same thing. The real question is when will you use one over the other.



          You use DbSet when you know the type of entity you want to play with. You simple write the DbContext name then the entity type name and you can create, read, update or delete entries for this entity with the entity methods available. You know what you want and you know where to do it.



          You use Set when you don't know the entity type you want to play with. Lets say, you wanted to build a class that does your repository functions for creating, reading, updating and deleting entries for an entity. You want this class to be reusable so that you can just pass a DbContext on it and it will use the same create, read, update and delete methods. You don't know for sure what DbContext it will be used on or what DbSet the DbContext will have. Here's when you use generics so that your class can be used by any DbContext for any DbSet.



          Here's an example of a class you can use for creating any entity on any DbSet in any DbContext



          public class Repository<TDbContext> where TDbContext : DbContext
          {
          private TDbContext _context { get; }

          public Repository(TDbContext context)
          {
          _context = context;
          }

          public TEntity Create<TEntity>(TEntity entity) where TEntity : class
          {
          if(entity != null)
          {
          var dataSet = _context.Set<TEntity>();

          if(entity is IEnumerable)
          {
          dataSet.AddRange(entity);
          }
          else
          {
          dataSet.Add(entity);
          }

          _context.SaveChanges();


          }

          return entity;
          }
          }


          And this is how to use it.



          var dbContext01 = new DbContext01();
          var dbContext02 = new DbContext02();

          var repository01 = new Repository<DbContext01>(dbContext01);
          var repository02 = new Repository<DbContext02>(dbContext02);

          repository01.Create(new EntityOnDbContext01 {
          Property01A = "String",
          Property01B = "String"
          });

          repository02.Create(new EntityOnDbContext02 {
          Property02A = 12345,
          Property02B = 12345
          });


          Here's a link if you want to know more about generics. Its super awesome.



          https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/






          share|improve this answer


























            3












            3








            3







            They do exactly the same thing. The real question is when will you use one over the other.



            You use DbSet when you know the type of entity you want to play with. You simple write the DbContext name then the entity type name and you can create, read, update or delete entries for this entity with the entity methods available. You know what you want and you know where to do it.



            You use Set when you don't know the entity type you want to play with. Lets say, you wanted to build a class that does your repository functions for creating, reading, updating and deleting entries for an entity. You want this class to be reusable so that you can just pass a DbContext on it and it will use the same create, read, update and delete methods. You don't know for sure what DbContext it will be used on or what DbSet the DbContext will have. Here's when you use generics so that your class can be used by any DbContext for any DbSet.



            Here's an example of a class you can use for creating any entity on any DbSet in any DbContext



            public class Repository<TDbContext> where TDbContext : DbContext
            {
            private TDbContext _context { get; }

            public Repository(TDbContext context)
            {
            _context = context;
            }

            public TEntity Create<TEntity>(TEntity entity) where TEntity : class
            {
            if(entity != null)
            {
            var dataSet = _context.Set<TEntity>();

            if(entity is IEnumerable)
            {
            dataSet.AddRange(entity);
            }
            else
            {
            dataSet.Add(entity);
            }

            _context.SaveChanges();


            }

            return entity;
            }
            }


            And this is how to use it.



            var dbContext01 = new DbContext01();
            var dbContext02 = new DbContext02();

            var repository01 = new Repository<DbContext01>(dbContext01);
            var repository02 = new Repository<DbContext02>(dbContext02);

            repository01.Create(new EntityOnDbContext01 {
            Property01A = "String",
            Property01B = "String"
            });

            repository02.Create(new EntityOnDbContext02 {
            Property02A = 12345,
            Property02B = 12345
            });


            Here's a link if you want to know more about generics. Its super awesome.



            https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/






            share|improve this answer













            They do exactly the same thing. The real question is when will you use one over the other.



            You use DbSet when you know the type of entity you want to play with. You simple write the DbContext name then the entity type name and you can create, read, update or delete entries for this entity with the entity methods available. You know what you want and you know where to do it.



            You use Set when you don't know the entity type you want to play with. Lets say, you wanted to build a class that does your repository functions for creating, reading, updating and deleting entries for an entity. You want this class to be reusable so that you can just pass a DbContext on it and it will use the same create, read, update and delete methods. You don't know for sure what DbContext it will be used on or what DbSet the DbContext will have. Here's when you use generics so that your class can be used by any DbContext for any DbSet.



            Here's an example of a class you can use for creating any entity on any DbSet in any DbContext



            public class Repository<TDbContext> where TDbContext : DbContext
            {
            private TDbContext _context { get; }

            public Repository(TDbContext context)
            {
            _context = context;
            }

            public TEntity Create<TEntity>(TEntity entity) where TEntity : class
            {
            if(entity != null)
            {
            var dataSet = _context.Set<TEntity>();

            if(entity is IEnumerable)
            {
            dataSet.AddRange(entity);
            }
            else
            {
            dataSet.Add(entity);
            }

            _context.SaveChanges();


            }

            return entity;
            }
            }


            And this is how to use it.



            var dbContext01 = new DbContext01();
            var dbContext02 = new DbContext02();

            var repository01 = new Repository<DbContext01>(dbContext01);
            var repository02 = new Repository<DbContext02>(dbContext02);

            repository01.Create(new EntityOnDbContext01 {
            Property01A = "String",
            Property01B = "String"
            });

            repository02.Create(new EntityOnDbContext02 {
            Property02A = 12345,
            Property02B = 12345
            });


            Here's a link if you want to know more about generics. Its super awesome.



            https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 25 '18 at 17:29









            calingasancalingasan

            32423




            32423

























                2














                Unfortunately currently you won't find explanation in the official documentation, mainly because all these are functionally equivalent.



                First, the generic methods of DbConext like Add<TEntity>, Remove<TEntity>, Attach<TEntity> etc. a fully equivalent of the corresponding DbSet<TEntity> methods (actually currently they are the implementation of the later, i.e. DbSet methods simply call the corresponding DbContext generic method). Which one you use is just a matter of taste.



                Second, DbSet<TEntity> property and Set<TEntity> method are functionally equivalent, but do have some non functional differences.



                The DbSet properties are populated once at the context creation, while Set method always performs a lookup, so DbSet property access should be faster than Set method (although not significant).



                The important difference is actually the EF Core Including & Excluding Types convention:




                By convention, types that are exposed in DbSet properties on your context are included in your model. In addition, types that are mentioned in the OnModelCreating method are also included.




                So while you can keep your DbContext without exposed DbSet properties and work just with Set method, if you do so you have to tell explicitly EF Core which are your entity types by adding in OnModelCreating a call to modelBuilder.Entity<TEntity>(); for each entity type (this is what the documentation does mean by types that are mentioned in the OnModelCreating method).






                share|improve this answer




























                  2














                  Unfortunately currently you won't find explanation in the official documentation, mainly because all these are functionally equivalent.



                  First, the generic methods of DbConext like Add<TEntity>, Remove<TEntity>, Attach<TEntity> etc. a fully equivalent of the corresponding DbSet<TEntity> methods (actually currently they are the implementation of the later, i.e. DbSet methods simply call the corresponding DbContext generic method). Which one you use is just a matter of taste.



                  Second, DbSet<TEntity> property and Set<TEntity> method are functionally equivalent, but do have some non functional differences.



                  The DbSet properties are populated once at the context creation, while Set method always performs a lookup, so DbSet property access should be faster than Set method (although not significant).



                  The important difference is actually the EF Core Including & Excluding Types convention:




                  By convention, types that are exposed in DbSet properties on your context are included in your model. In addition, types that are mentioned in the OnModelCreating method are also included.




                  So while you can keep your DbContext without exposed DbSet properties and work just with Set method, if you do so you have to tell explicitly EF Core which are your entity types by adding in OnModelCreating a call to modelBuilder.Entity<TEntity>(); for each entity type (this is what the documentation does mean by types that are mentioned in the OnModelCreating method).






                  share|improve this answer


























                    2












                    2








                    2







                    Unfortunately currently you won't find explanation in the official documentation, mainly because all these are functionally equivalent.



                    First, the generic methods of DbConext like Add<TEntity>, Remove<TEntity>, Attach<TEntity> etc. a fully equivalent of the corresponding DbSet<TEntity> methods (actually currently they are the implementation of the later, i.e. DbSet methods simply call the corresponding DbContext generic method). Which one you use is just a matter of taste.



                    Second, DbSet<TEntity> property and Set<TEntity> method are functionally equivalent, but do have some non functional differences.



                    The DbSet properties are populated once at the context creation, while Set method always performs a lookup, so DbSet property access should be faster than Set method (although not significant).



                    The important difference is actually the EF Core Including & Excluding Types convention:




                    By convention, types that are exposed in DbSet properties on your context are included in your model. In addition, types that are mentioned in the OnModelCreating method are also included.




                    So while you can keep your DbContext without exposed DbSet properties and work just with Set method, if you do so you have to tell explicitly EF Core which are your entity types by adding in OnModelCreating a call to modelBuilder.Entity<TEntity>(); for each entity type (this is what the documentation does mean by types that are mentioned in the OnModelCreating method).






                    share|improve this answer













                    Unfortunately currently you won't find explanation in the official documentation, mainly because all these are functionally equivalent.



                    First, the generic methods of DbConext like Add<TEntity>, Remove<TEntity>, Attach<TEntity> etc. a fully equivalent of the corresponding DbSet<TEntity> methods (actually currently they are the implementation of the later, i.e. DbSet methods simply call the corresponding DbContext generic method). Which one you use is just a matter of taste.



                    Second, DbSet<TEntity> property and Set<TEntity> method are functionally equivalent, but do have some non functional differences.



                    The DbSet properties are populated once at the context creation, while Set method always performs a lookup, so DbSet property access should be faster than Set method (although not significant).



                    The important difference is actually the EF Core Including & Excluding Types convention:




                    By convention, types that are exposed in DbSet properties on your context are included in your model. In addition, types that are mentioned in the OnModelCreating method are also included.




                    So while you can keep your DbContext without exposed DbSet properties and work just with Set method, if you do so you have to tell explicitly EF Core which are your entity types by adding in OnModelCreating a call to modelBuilder.Entity<TEntity>(); for each entity type (this is what the documentation does mean by types that are mentioned in the OnModelCreating method).







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 25 '18 at 18:21









                    Ivan StoevIvan Stoev

                    107k784137




                    107k784137























                        0














                        They are the same and actually returns the same DbSet instance.



                        var options = //...;

                        using (var ctx = new FooContext(options))
                        {
                        // true
                        bool isSame = ReferenceEquals(ctx.Bars, ctx.Set<Bar>());
                        }


                        One use case for not including a DbSet property in your DbContext is when you want to hide an entity type from a consumer. (e.g. an entity that acts as join table for many-to-many relationship). You can then mark the entity as internal class so consumers also can't also access it using Set<>.



                        Also, if you don't expose a DbSet property, you need to explicitly configure the entity or you'll get the following exception:



                        //throws System.InvalidOperationException: 'The entity type 'Foo' was not found. Ensure that the entity type has been added to the model.'
                        ctx.Set<Foo>().Add(new Foo());





                        share|improve this answer




























                          0














                          They are the same and actually returns the same DbSet instance.



                          var options = //...;

                          using (var ctx = new FooContext(options))
                          {
                          // true
                          bool isSame = ReferenceEquals(ctx.Bars, ctx.Set<Bar>());
                          }


                          One use case for not including a DbSet property in your DbContext is when you want to hide an entity type from a consumer. (e.g. an entity that acts as join table for many-to-many relationship). You can then mark the entity as internal class so consumers also can't also access it using Set<>.



                          Also, if you don't expose a DbSet property, you need to explicitly configure the entity or you'll get the following exception:



                          //throws System.InvalidOperationException: 'The entity type 'Foo' was not found. Ensure that the entity type has been added to the model.'
                          ctx.Set<Foo>().Add(new Foo());





                          share|improve this answer


























                            0












                            0








                            0







                            They are the same and actually returns the same DbSet instance.



                            var options = //...;

                            using (var ctx = new FooContext(options))
                            {
                            // true
                            bool isSame = ReferenceEquals(ctx.Bars, ctx.Set<Bar>());
                            }


                            One use case for not including a DbSet property in your DbContext is when you want to hide an entity type from a consumer. (e.g. an entity that acts as join table for many-to-many relationship). You can then mark the entity as internal class so consumers also can't also access it using Set<>.



                            Also, if you don't expose a DbSet property, you need to explicitly configure the entity or you'll get the following exception:



                            //throws System.InvalidOperationException: 'The entity type 'Foo' was not found. Ensure that the entity type has been added to the model.'
                            ctx.Set<Foo>().Add(new Foo());





                            share|improve this answer













                            They are the same and actually returns the same DbSet instance.



                            var options = //...;

                            using (var ctx = new FooContext(options))
                            {
                            // true
                            bool isSame = ReferenceEquals(ctx.Bars, ctx.Set<Bar>());
                            }


                            One use case for not including a DbSet property in your DbContext is when you want to hide an entity type from a consumer. (e.g. an entity that acts as join table for many-to-many relationship). You can then mark the entity as internal class so consumers also can't also access it using Set<>.



                            Also, if you don't expose a DbSet property, you need to explicitly configure the entity or you'll get the following exception:



                            //throws System.InvalidOperationException: 'The entity type 'Foo' was not found. Ensure that the entity type has been added to the model.'
                            ctx.Set<Foo>().Add(new Foo());






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 25 '18 at 17:36









                            Paolo GoPaolo Go

                            1,479622




                            1,479622






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53469498%2fdifference-between-dbsett-property-and-sett-function-in-ef-core%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Wiesbaden

                                Marschland

                                Dieringhausen