locked
EF - Generic save method RRS feed

  • Question

  • Hi,

    I'm trying to save objects to a database using EF6 with a generic method.

    The method looks like this:

            private void SaveDBChanges<T>(T entity) where T : class
            {
                using (var context = new DataContextProduction())
                {                
                    context.Set<T>().Add(entity);
                    context.SaveChanges(); 
                }
            }

    And the call to the method looks like this:

                    object myObject = new DatabaseItemObject();                 
                    SaveDBChanges(myObject);

    When the context.Set<> command is executed the following message appear: "The entity type Object is not part of the model for the current context"

    Is there any good way to save objects like this using EF or do the objects need to be casted to the correct type before they are saved?

    Monday, May 29, 2017 10:45 AM

Answers

  • Solution was to change:

    context.Set<T>().Add(entity);
    to:

    Type type = entity.GetType();
    context.Set(type).Add(entity);          


    Monday, May 29, 2017 10:55 AM

All replies

  • Solution was to change:

    context.Set<T>().Add(entity);
    to:

    Type type = entity.GetType();
    context.Set(type).Add(entity);          


    Monday, May 29, 2017 10:55 AM
  • Hi AsusT9,

    Thanks for your sharing. Please mark the reply as answer.

    This will be beneficial to community members who facing the same questions.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, May 30, 2017 1:59 AM