Link to home
Start Free TrialLog in
Avatar of Ruffone
Ruffone

asked on

Add methid works but Create method don't

I have these 2 functions "Add" is a test which works to add the data to the database. It works as expected but "Create" does not. Could anyone help me to figure out why.

Thanks

    Public Function Add(ByVal itemToAdd As TObject) As TObject
        Dim addedItem As TObject = DbSet.Add(itemToAdd)
        dbContext.SaveChanges()
        Return addedItem
    End Function

    Public Overridable Function Create(t As TObject) As TObject Implements IRepository(Of TObject).Create
        Dim newEntry As TObject = DbSet.Add(t)
        dbContext.Entry(t).State = EntityState.Added
        If Not shareContext Then dbContext.SaveChanges()
        Return newEntry
    End Function

Open in new window

Avatar of Ioannis Paraskevopoulos
Ioannis Paraskevopoulos
Flag of Greece image

Hi,

We would need a bit more information. When you say it does not work, does it mean it does not save or is there any kind of exception?

I see you also have an if statement with a variable that it is not clear how is it set. Are you certain it has the expected value when it checks it?

Giannis
Avatar of Ruffone
Ruffone

ASKER

Thanks for responding. What I meant by not working is that the entity was not saved to the DB. I converted the code to VB.net and was relying on converter assumptions in the "IF" statement. The variable "shareContext" is set to true in the constructor and is used to direct garbage collection. I was able to get the entity to save to the database with the code below. as for the garbage collection, I don't know if it is affected poorly

        Dim newEntry As TObject = DbSet.Add(t)
        If Not shareContext = False Then dbContext.SaveChanges()
        Return newEntry

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.