jbogard / ContosoUniversityCore

MIT License
591 stars 151 forks source link

DbContext SaveChangesAsync not committing right away #10

Closed kjbetz closed 7 years ago

kjbetz commented 7 years ago

When I call .SaveChangesAsync() on my EF Core context, should it be inserting into the database right away?

Or... is this a problem with the DbContext filter set up?

Here's how my code looks in a Features.Videos.Upload class...

Video video = new Vidoe();
video.Id = Guid.NewGuid();

// some more processing and more mapping of properties

await _db.Videos.AddAsync(video);
await _db.SaveChangesAsync();

Following the code, after the SaveChangesAsync() call, the logging shows the INSERT SQL statement. But there is no data in the database.

The data doesn't appear in the database until it goes through the Transaction Filter and hits the _currentTransaction?.Commit() method call in the CommitTransactionAsync() method.

The reason why this is a problem (I think).. is because I'm trying to save the video first, so I can then process some tags associated with it. When this code is called:

_db.TagVideos.AddAsync(new TagVideo { TagId = tagId, VideoId = videoId });

It too is generating an INSERT statement in the logger but then I'm getting an exception for a forein key constraint because the Video doesn't exist yet in the database.

Is this a problem with the Filter set up, EF Core, my Code...?

Thanks for any insight!

kjbetz commented 7 years ago

It was my code...

I guess with join entities I need to add them with both entity objects. I changed it to be: _db.TagVideos.AddAsync(new TagVideo { Tag = tag, Video = video }); and it worked. I guess maybe that's how Entity Framework tracks it correctly?