Saving a new record to the database

It is time to add some data to our table in the created database. We will insert a row, which is sometimes called a record. A record in the People table consists of values in three columns: PersonId, FirstName, and LastName. These values are going to be based on property values of an instance of the Person class, which is mapped to the People table. This is an important concept to remember. When we create entity classes, their purpose is to map to tables. There are some exceptions to this rule, which we will see in later chapters. This table is represented by a collection-based property in our Context class.

This property's type is DbSet of Person and its name is People. Conceptually, you can think of adding objects to that collection to be equivalent to inserting rows into the database's corresponding table. You need to use the Add method of DbSet to implement the addition of new data. The DbContext class has the SaveChanges method, which is responsible for committing all the pending changes to the database. It does so by examining the state of all the objects in the context. All such objects are housed within each of the collection properties based on DbSet in the context class. In our case, there is only one such collection in the Context class: the People property. Context tracks the state of each one of the objects in all its DbSet properties. This state can be "Deleted", "Added", "Modified", or "Unchanged". We can easily decipher how each of the states, with the exception of "Unchanged", will result in a corresponding query sent to the RDMBS. If you want to create multiple rows in a table, you just need to add multiple instances of. NET object based on the class that corresponds to the table in question. The next step is to commit your changes to the database using the SaveChanges method. This method runs as a single transaction. As a result, all pending database changes are persisted as a single unit of work, participating in this transaction. If one of the commits fails, the entire batch of changes will be rolled back upon exception. The DbContext.SaveChanges method is transactional. This enables you to commit a batch of logically related changes as a single operation, thus ensuring transactional consistency and data integrity.

Let's take a look at the code that adds a row to the People table:

static void Main(string[] args)
{
    using (var context = new Context())
    {
        context.Database.CreateIfNotExists();
        var person = new Person
        {
            FirstName = "John",
            LastName = "Doe"
        };
        context.People.Add(person);
        context.SaveChanges();
    }
}

In this sample code, we are creating a new instance of the Person class, populating the first and last names. You will notice that we did not set a value for the PersonId property. The reason for this is that this property corresponds to the identity column in SQL Server, which means its value is generated by the database. This value will be automatically populated in the person variable's object immediately after the save. You can verify this by setting a breakpoint on the line after the SaveChanges call, and checking the value of the PersonId property of the person variable. Another thing to notice is that the instance of the Context class is wrapped inside the Using statement. It is important to always follow this coding pattern. DbContext implements an IDisposable interface. It does so because it contains an instance of DbConnection that points to the database specified in the connection string. It is very important to properly dispose of the database connection in Entity Framework, just like it was important in ADO.NET. Here is the same code in VB.NET:

Sub Main()
    Using context = New Context()
    context.Database.CreateIfNotExists()
        Dim person = New Person With {
            .FirstName = "John",
            .LastName = "Doe"
        }
    context.People.Add(person)
    context.SaveChanges()
    End Using
End Sub

If you would like to add one more row, just create another instance of the Person class and add it to the same People collection. To verify that the data was successfully inserted, you can just open SQL Server Management Studio or SQL Server Object Explorer inside Visual Studio, and look at the data in the People table. Now, let's see how we can retrieve the data in the database using Entity Framework.

Tip

SQL Server Object Explorer can be found under the View menu in Visual Studio. If you cannot find this window, you may need to install SSDT or SQL Server Data Tools from https://msdn.microsoft.com/en-us/data/tools.aspx.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.36.38