Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

Entity Framework 6 and Persisting Record to DB

1.36/5 (3 votes)
4 Oct 2016CPOL2 min read 8K  
Entity framework 6 and persisting record to database

I have given myself a new ASP.NET Core project, with a backend Microsoft SQL relationship database.

Normally, I would create my own Entity Classe, use a DataContext connection and work from there (Complex Linq). This project is new and entity framework has moved on since the last time I used it.

It did not take long for me to find my first problem. The idea and logic is simple but EF did not want to make it simple.

I have two tables, which has a one to many relationship and I needed to insert a parent and child record within the same post.

Normally I would do this using the below logic, but EF gave me an error saying that the parent id did not exist within the database.

If you have an Order system, the Parent could be the transaction record and the child could be the multiple items on the order, linked to the transactions.

private static void basiceLogic()
  {
      int parentId = addMain("Food order");
      int childId = addChild(parentId, "Pizza",5.99);
      childId = addChild(parentId, "Chips",1.99);

  }

 

Creating the Parent

private static int addMain(string name)
{
    using (var context = new DatabaseEntity())
    {
        var table = new DBMainTable() { Name = name,  };
        context.DBMainTable.Add(table);
        context.SaveChanges();

        return table.Id;

    }
}

Creating the Child

private static int addChild(int parentId, string name, decimal cost)
    {
        using (var context = new DatabaseEntity())
        {
            var table = new DBChildTable() { Name = name, Cost = cost };
            context.DBChildTable.Add(table);
            context.SaveChanges();

            return table.Id;

        }
    }

 

My Resolve
Went back and forth on Stackoverflow and other site and could not find a resolve, but in the end I found out why and the below code resolved my issue

 

Create a global Database context
 

Models.Database.DatabaseEntity context;

Basic logic

private static void basiceLogic()
    {
        context = new Models.Database.DatabaseEntity(); 

      int parentId = addMain("Food order");

        //Dispose the current context and connection to db.
        //This then will persist the record to the db (Insert,Updated or deleted)
        //Then create new record
       context.Dispose();
        context = new Models.Blog.blogEntity();

        int childId = addChild(parentId, "Pizza",5.99);
        childId = addChild(parentId, "Chips",1.99);

       context.Dispose();
    }

 

Creating the Parent

private static int addMain(string name)
  {

          var table = new DBMainTable() { Name = name,  };
          context.DBMainTable.Add(table);
          context.SaveChanges();

          return table.Id;


  }

 

Creating the Child

private static int addChild(int parentId, string name, decimal cost)
    {
       
            var table = new DBChildTable() { Name = name, Cost = cost };
            context.DBChildTable.Add(table);
            context.SaveChanges();

            return table.Id;

    
    }

Reason
When you use the "USING" element, this does not DISPOSE and close the connection to the current context connection.
Because of this, the parent record does not get persisted to the database and it wont be available for relationship required by the child record.
By doing the physical Dispose and reload of the context, it forces the parent record into the DB and creates a new connection for the EF with the Database and the child will see the relationship on insert.

Idea or Points
There is a hundred ways to screw a light bulb, so if someone has had this issue and resolved this another way.
Please comment and let me know.
Thanks

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)