Mocking or faking DbEntityEntry or creating a new DbEntityEntry





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







60















Following on the heels of my other question about mocking DbContext.Set I've got another question about mocking EF Code First.



I now have a method for my update that looks like:



if (entity == null)
throw new ArgumentNullException("entity");

Context.GetIDbSet<T>().Attach(entity);
Context.Entry(entity).State = EntityState.Modified;
Context.CommitChanges();

return entity;


Context is an interface of my own DbContext.



The problem I'm running in to is, how do I handle the



Context.Entry(entity).State.



I've stepped through this code and it works when I have a real live DbContext as the implementation of my Context interface. But when I put my fake context there, I don't know how to handle it.



There is no constructor for a DbEntityEntry class, so I can't just create a new one in my fake context.



Has anyone had any success with either mocking or faking DbEntityEntry in your CodeFirst solutions?



Or is there a better way to handle the state changes?










share|improve this question































    60















    Following on the heels of my other question about mocking DbContext.Set I've got another question about mocking EF Code First.



    I now have a method for my update that looks like:



    if (entity == null)
    throw new ArgumentNullException("entity");

    Context.GetIDbSet<T>().Attach(entity);
    Context.Entry(entity).State = EntityState.Modified;
    Context.CommitChanges();

    return entity;


    Context is an interface of my own DbContext.



    The problem I'm running in to is, how do I handle the



    Context.Entry(entity).State.



    I've stepped through this code and it works when I have a real live DbContext as the implementation of my Context interface. But when I put my fake context there, I don't know how to handle it.



    There is no constructor for a DbEntityEntry class, so I can't just create a new one in my fake context.



    Has anyone had any success with either mocking or faking DbEntityEntry in your CodeFirst solutions?



    Or is there a better way to handle the state changes?










    share|improve this question



























      60












      60








      60


      12






      Following on the heels of my other question about mocking DbContext.Set I've got another question about mocking EF Code First.



      I now have a method for my update that looks like:



      if (entity == null)
      throw new ArgumentNullException("entity");

      Context.GetIDbSet<T>().Attach(entity);
      Context.Entry(entity).State = EntityState.Modified;
      Context.CommitChanges();

      return entity;


      Context is an interface of my own DbContext.



      The problem I'm running in to is, how do I handle the



      Context.Entry(entity).State.



      I've stepped through this code and it works when I have a real live DbContext as the implementation of my Context interface. But when I put my fake context there, I don't know how to handle it.



      There is no constructor for a DbEntityEntry class, so I can't just create a new one in my fake context.



      Has anyone had any success with either mocking or faking DbEntityEntry in your CodeFirst solutions?



      Or is there a better way to handle the state changes?










      share|improve this question
















      Following on the heels of my other question about mocking DbContext.Set I've got another question about mocking EF Code First.



      I now have a method for my update that looks like:



      if (entity == null)
      throw new ArgumentNullException("entity");

      Context.GetIDbSet<T>().Attach(entity);
      Context.Entry(entity).State = EntityState.Modified;
      Context.CommitChanges();

      return entity;


      Context is an interface of my own DbContext.



      The problem I'm running in to is, how do I handle the



      Context.Entry(entity).State.



      I've stepped through this code and it works when I have a real live DbContext as the implementation of my Context interface. But when I put my fake context there, I don't know how to handle it.



      There is no constructor for a DbEntityEntry class, so I can't just create a new one in my fake context.



      Has anyone had any success with either mocking or faking DbEntityEntry in your CodeFirst solutions?



      Or is there a better way to handle the state changes?







      entity-framework ef-code-first






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 23 '17 at 11:54









      Community

      11




      11










      asked Feb 17 '11 at 22:13









      taylonrtaylonr

      9,23053063




      9,23053063
























          2 Answers
          2






          active

          oldest

          votes


















          92














          Just like the other case, what you need is to add an additional level of indirection:



          interface ISalesContext
          {
          IDbSet<T> GetIDbSet<T>();
          void SetModified(object entity)
          }

          class SalesContext : DbContext, ISalesContext
          {
          public IDbSet<T> GetIDbSet<T>()
          {
          return Set<T>();
          }

          public void SetModified(object entity)
          {
          Entry(entity).State = EntityState.Modified;
          }
          }


          So, instead of calling the implementation, you just call SetModified.






          share|improve this answer
























          • Thanks... I got stuck thinking "How do I mock Entry" when I don't need to, I just need to mock the modified functionality... I'm almost embarrassed it's so obvious now.

            – taylonr
            Feb 18 '11 at 13:57






          • 10





            Don't be - our lives as developers are filled with "duh!" moments :-)

            – Diego Mijelshon
            Feb 18 '11 at 15:09






          • 4





            +9000 I just spent an hour researching how to mock classes with internal ctors and internal classes. I was getting thwarted at every turn and the solution is so simple! Thanks to both the asker and the answerer

            – Darko Z
            May 20 '11 at 5:03













          • @DiegoMijelshon This is elegant!

            – devlord
            Oct 16 '13 at 22:36






          • 1





            @ErwinRooijakkers late response, but in your tests, you don't do anything. Just implement the SetModified in your fake of ISalesContext and leave it empty. Just public void SetModified(object entity){}

            – Nathan Koop
            Jun 19 '15 at 14:32



















          0














          Found this question when I needed to unit test with Moq, no need for your own interface. I wanted to set specific fields to not modified but the method SetModified can be used with object as well.



          DbContext:



          public class AppDbContext : DbContext
          {
          ...
          public virtual void SetModified(GuidEntityBase entity)
          {
          Entry(entity).State = EntityState.Modified;
          Entry(entity).Property(x => x.CreatedDate).IsModified = false;
          Entry(entity).Property(x => x.CreatedBy).IsModified = false;
          }
          ...
          }


          Test:



          var mockContext = new Mock<AppDbContext>();
          mockContext.Setup(c => c.MyDbSet).Returns(mockMyDbSet.Object);
          mockContext.Setup(c => c.SetModified(It.IsAny<GuidEntityBase>()));





          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%2f5035323%2fmocking-or-faking-dbentityentry-or-creating-a-new-dbentityentry%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            92














            Just like the other case, what you need is to add an additional level of indirection:



            interface ISalesContext
            {
            IDbSet<T> GetIDbSet<T>();
            void SetModified(object entity)
            }

            class SalesContext : DbContext, ISalesContext
            {
            public IDbSet<T> GetIDbSet<T>()
            {
            return Set<T>();
            }

            public void SetModified(object entity)
            {
            Entry(entity).State = EntityState.Modified;
            }
            }


            So, instead of calling the implementation, you just call SetModified.






            share|improve this answer
























            • Thanks... I got stuck thinking "How do I mock Entry" when I don't need to, I just need to mock the modified functionality... I'm almost embarrassed it's so obvious now.

              – taylonr
              Feb 18 '11 at 13:57






            • 10





              Don't be - our lives as developers are filled with "duh!" moments :-)

              – Diego Mijelshon
              Feb 18 '11 at 15:09






            • 4





              +9000 I just spent an hour researching how to mock classes with internal ctors and internal classes. I was getting thwarted at every turn and the solution is so simple! Thanks to both the asker and the answerer

              – Darko Z
              May 20 '11 at 5:03













            • @DiegoMijelshon This is elegant!

              – devlord
              Oct 16 '13 at 22:36






            • 1





              @ErwinRooijakkers late response, but in your tests, you don't do anything. Just implement the SetModified in your fake of ISalesContext and leave it empty. Just public void SetModified(object entity){}

              – Nathan Koop
              Jun 19 '15 at 14:32
















            92














            Just like the other case, what you need is to add an additional level of indirection:



            interface ISalesContext
            {
            IDbSet<T> GetIDbSet<T>();
            void SetModified(object entity)
            }

            class SalesContext : DbContext, ISalesContext
            {
            public IDbSet<T> GetIDbSet<T>()
            {
            return Set<T>();
            }

            public void SetModified(object entity)
            {
            Entry(entity).State = EntityState.Modified;
            }
            }


            So, instead of calling the implementation, you just call SetModified.






            share|improve this answer
























            • Thanks... I got stuck thinking "How do I mock Entry" when I don't need to, I just need to mock the modified functionality... I'm almost embarrassed it's so obvious now.

              – taylonr
              Feb 18 '11 at 13:57






            • 10





              Don't be - our lives as developers are filled with "duh!" moments :-)

              – Diego Mijelshon
              Feb 18 '11 at 15:09






            • 4





              +9000 I just spent an hour researching how to mock classes with internal ctors and internal classes. I was getting thwarted at every turn and the solution is so simple! Thanks to both the asker and the answerer

              – Darko Z
              May 20 '11 at 5:03













            • @DiegoMijelshon This is elegant!

              – devlord
              Oct 16 '13 at 22:36






            • 1





              @ErwinRooijakkers late response, but in your tests, you don't do anything. Just implement the SetModified in your fake of ISalesContext and leave it empty. Just public void SetModified(object entity){}

              – Nathan Koop
              Jun 19 '15 at 14:32














            92












            92








            92







            Just like the other case, what you need is to add an additional level of indirection:



            interface ISalesContext
            {
            IDbSet<T> GetIDbSet<T>();
            void SetModified(object entity)
            }

            class SalesContext : DbContext, ISalesContext
            {
            public IDbSet<T> GetIDbSet<T>()
            {
            return Set<T>();
            }

            public void SetModified(object entity)
            {
            Entry(entity).State = EntityState.Modified;
            }
            }


            So, instead of calling the implementation, you just call SetModified.






            share|improve this answer













            Just like the other case, what you need is to add an additional level of indirection:



            interface ISalesContext
            {
            IDbSet<T> GetIDbSet<T>();
            void SetModified(object entity)
            }

            class SalesContext : DbContext, ISalesContext
            {
            public IDbSet<T> GetIDbSet<T>()
            {
            return Set<T>();
            }

            public void SetModified(object entity)
            {
            Entry(entity).State = EntityState.Modified;
            }
            }


            So, instead of calling the implementation, you just call SetModified.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Feb 18 '11 at 0:19









            Diego MijelshonDiego Mijelshon

            48.9k11100139




            48.9k11100139













            • Thanks... I got stuck thinking "How do I mock Entry" when I don't need to, I just need to mock the modified functionality... I'm almost embarrassed it's so obvious now.

              – taylonr
              Feb 18 '11 at 13:57






            • 10





              Don't be - our lives as developers are filled with "duh!" moments :-)

              – Diego Mijelshon
              Feb 18 '11 at 15:09






            • 4





              +9000 I just spent an hour researching how to mock classes with internal ctors and internal classes. I was getting thwarted at every turn and the solution is so simple! Thanks to both the asker and the answerer

              – Darko Z
              May 20 '11 at 5:03













            • @DiegoMijelshon This is elegant!

              – devlord
              Oct 16 '13 at 22:36






            • 1





              @ErwinRooijakkers late response, but in your tests, you don't do anything. Just implement the SetModified in your fake of ISalesContext and leave it empty. Just public void SetModified(object entity){}

              – Nathan Koop
              Jun 19 '15 at 14:32



















            • Thanks... I got stuck thinking "How do I mock Entry" when I don't need to, I just need to mock the modified functionality... I'm almost embarrassed it's so obvious now.

              – taylonr
              Feb 18 '11 at 13:57






            • 10





              Don't be - our lives as developers are filled with "duh!" moments :-)

              – Diego Mijelshon
              Feb 18 '11 at 15:09






            • 4





              +9000 I just spent an hour researching how to mock classes with internal ctors and internal classes. I was getting thwarted at every turn and the solution is so simple! Thanks to both the asker and the answerer

              – Darko Z
              May 20 '11 at 5:03













            • @DiegoMijelshon This is elegant!

              – devlord
              Oct 16 '13 at 22:36






            • 1





              @ErwinRooijakkers late response, but in your tests, you don't do anything. Just implement the SetModified in your fake of ISalesContext and leave it empty. Just public void SetModified(object entity){}

              – Nathan Koop
              Jun 19 '15 at 14:32

















            Thanks... I got stuck thinking "How do I mock Entry" when I don't need to, I just need to mock the modified functionality... I'm almost embarrassed it's so obvious now.

            – taylonr
            Feb 18 '11 at 13:57





            Thanks... I got stuck thinking "How do I mock Entry" when I don't need to, I just need to mock the modified functionality... I'm almost embarrassed it's so obvious now.

            – taylonr
            Feb 18 '11 at 13:57




            10




            10





            Don't be - our lives as developers are filled with "duh!" moments :-)

            – Diego Mijelshon
            Feb 18 '11 at 15:09





            Don't be - our lives as developers are filled with "duh!" moments :-)

            – Diego Mijelshon
            Feb 18 '11 at 15:09




            4




            4





            +9000 I just spent an hour researching how to mock classes with internal ctors and internal classes. I was getting thwarted at every turn and the solution is so simple! Thanks to both the asker and the answerer

            – Darko Z
            May 20 '11 at 5:03







            +9000 I just spent an hour researching how to mock classes with internal ctors and internal classes. I was getting thwarted at every turn and the solution is so simple! Thanks to both the asker and the answerer

            – Darko Z
            May 20 '11 at 5:03















            @DiegoMijelshon This is elegant!

            – devlord
            Oct 16 '13 at 22:36





            @DiegoMijelshon This is elegant!

            – devlord
            Oct 16 '13 at 22:36




            1




            1





            @ErwinRooijakkers late response, but in your tests, you don't do anything. Just implement the SetModified in your fake of ISalesContext and leave it empty. Just public void SetModified(object entity){}

            – Nathan Koop
            Jun 19 '15 at 14:32





            @ErwinRooijakkers late response, but in your tests, you don't do anything. Just implement the SetModified in your fake of ISalesContext and leave it empty. Just public void SetModified(object entity){}

            – Nathan Koop
            Jun 19 '15 at 14:32













            0














            Found this question when I needed to unit test with Moq, no need for your own interface. I wanted to set specific fields to not modified but the method SetModified can be used with object as well.



            DbContext:



            public class AppDbContext : DbContext
            {
            ...
            public virtual void SetModified(GuidEntityBase entity)
            {
            Entry(entity).State = EntityState.Modified;
            Entry(entity).Property(x => x.CreatedDate).IsModified = false;
            Entry(entity).Property(x => x.CreatedBy).IsModified = false;
            }
            ...
            }


            Test:



            var mockContext = new Mock<AppDbContext>();
            mockContext.Setup(c => c.MyDbSet).Returns(mockMyDbSet.Object);
            mockContext.Setup(c => c.SetModified(It.IsAny<GuidEntityBase>()));





            share|improve this answer




























              0














              Found this question when I needed to unit test with Moq, no need for your own interface. I wanted to set specific fields to not modified but the method SetModified can be used with object as well.



              DbContext:



              public class AppDbContext : DbContext
              {
              ...
              public virtual void SetModified(GuidEntityBase entity)
              {
              Entry(entity).State = EntityState.Modified;
              Entry(entity).Property(x => x.CreatedDate).IsModified = false;
              Entry(entity).Property(x => x.CreatedBy).IsModified = false;
              }
              ...
              }


              Test:



              var mockContext = new Mock<AppDbContext>();
              mockContext.Setup(c => c.MyDbSet).Returns(mockMyDbSet.Object);
              mockContext.Setup(c => c.SetModified(It.IsAny<GuidEntityBase>()));





              share|improve this answer


























                0












                0








                0







                Found this question when I needed to unit test with Moq, no need for your own interface. I wanted to set specific fields to not modified but the method SetModified can be used with object as well.



                DbContext:



                public class AppDbContext : DbContext
                {
                ...
                public virtual void SetModified(GuidEntityBase entity)
                {
                Entry(entity).State = EntityState.Modified;
                Entry(entity).Property(x => x.CreatedDate).IsModified = false;
                Entry(entity).Property(x => x.CreatedBy).IsModified = false;
                }
                ...
                }


                Test:



                var mockContext = new Mock<AppDbContext>();
                mockContext.Setup(c => c.MyDbSet).Returns(mockMyDbSet.Object);
                mockContext.Setup(c => c.SetModified(It.IsAny<GuidEntityBase>()));





                share|improve this answer













                Found this question when I needed to unit test with Moq, no need for your own interface. I wanted to set specific fields to not modified but the method SetModified can be used with object as well.



                DbContext:



                public class AppDbContext : DbContext
                {
                ...
                public virtual void SetModified(GuidEntityBase entity)
                {
                Entry(entity).State = EntityState.Modified;
                Entry(entity).Property(x => x.CreatedDate).IsModified = false;
                Entry(entity).Property(x => x.CreatedBy).IsModified = false;
                }
                ...
                }


                Test:



                var mockContext = new Mock<AppDbContext>();
                mockContext.Setup(c => c.MyDbSet).Returns(mockMyDbSet.Object);
                mockContext.Setup(c => c.SetModified(It.IsAny<GuidEntityBase>()));






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 3 at 14:15









                OgglasOgglas

                16.5k7102138




                16.5k7102138






























                    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%2f5035323%2fmocking-or-faking-dbentityentry-or-creating-a-new-dbentityentry%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

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith