Click here to Skip to main content
15,886,060 members
Articles / All Topics

Entity Framework 6 and Persisting Record to DB

Rate me:
Please Sign up or sign in to vote.
1.36/5 (3 votes)
3 Oct 2016CPOL2 min read 7.6K   1   7
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)


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionEF use Unit of Work Pattern Pin
Ankit Rana2-Oct-16 18:06
Ankit Rana2-Oct-16 18:06 
GeneralRe: EF use Unit of Work Pattern Pin
Thomas Cooper3-Oct-16 2:51
Thomas Cooper3-Oct-16 2:51 
GeneralRe: EF use Unit of Work Pattern Pin
Ankit Rana3-Oct-16 18:04
Ankit Rana3-Oct-16 18:04 
GeneralRe: EF use Unit of Work Pattern Pin
Thomas Cooper3-Oct-16 21:52
Thomas Cooper3-Oct-16 21:52 
Would that not break the fixed one to many relationship, between the tables?
GeneralRe: EF use Unit of Work Pattern Pin
Ankit Rana3-Oct-16 22:07
Ankit Rana3-Oct-16 22:07 
QuestionTransactions Pin
gicalle7530-Sep-16 8:47
professionalgicalle7530-Sep-16 8:47 
AnswerRe: Transactions Pin
Chris Cooper30-Sep-16 22:07
Chris Cooper30-Sep-16 22:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.