Faizan Haroon
Faizan Haroon

Reputation: 107

Entity framework inserting to 3 tables the right way and rollback if exception

I have a very simple question and I am bangging my head on how to do it EXACTLY right. USING ENTITY FRAMEWORK AND ALSO TRYING REPOSITORY PATTERN NOW I have 3 tables:

Story id PRIMARY KEY IDENTITY
Album id PRIMARY KEY IDENTITY
Photo id PRIMARY KEY IDENTITY

I want to INSERT a new story like this:

 _db.Repository.Insert(oneStory);
      Save(); // Save will save it to table story
       oneStory.id; // return id of last added row.

Then using id of recently added story I want to save album like this

oneAlbum.fk_storyid=oneStory.id
    _db.Repository.Insert(oneAlbum);
          Save(); // Save will save it to table album
            oneAlbum.id; // return id of last added row.

Then using id of recently added album I want to save photo like this

onePhoto.fk_albumid=oneAlbum.id
    _db.Repository.Insert(onePhoto);
          Save(); // Save will save it to table photo
            onePhoto.id; // return id of last added row.

Here is the problem

So can some one guide me here how its done PERFECT which will save time and less code and also good structure. Thankyou.

Upvotes: 1

Views: 549

Answers (1)

Anders Abel
Anders Abel

Reputation: 69260

In Entity framework the DbContext itself is both a repository and a unit of work.

If you want to build additional repositories on top of that, you should inject the DbContext into them so that all operations use the same DbContext and you only call SaveChanges once.

In that case you should use navigation properties to link the objects to eachother instead of the foreign key - since you don't have any key values yet. EF will automatically insert things in the right order and assign values to the foreign keys.

If that's not an option, you can use a TransactionScope to wrap everything in one transaction:

using(var tx = new TransactionScope())
{
  _db.Repository.Insert(oneStory);
  Save(); // Save will save it to table story
  oneStory.id; // return id of last added row.

  _db.Repository.Insert(oneStory);
  Save(); // Save will save it to table story
  oneStory.id; // return id of last added row.

  onePhoto.fk_albumid=oneAlbum.id
  _db.Repository.Insert(onePhoto);
  Save(); // Save will save it to table photo
  onePhoto.id; // return id of last added row.

  tx.Complete();
}

Upvotes: 2

Related Questions