Introduction
In the previous article, we showed how you would create an object and save it, thereby creating a database table along with any record you choose. In the previous example, even though we set the Id of the record, it would overwrite and create a new record with a new primary identity. With this example. I am planning on showing you how you would update records. Let's first recap the code from the previous example.
static void Main(string[] args)
{
string sConn = "Data Source=<Your Server>;Initial Catalog=Shop;Integrated Security=True";
using (var ctx = new Shop(sConn))
{
Customer oCust = new Customer();
oCust.CustomerID = 1;
oCust.FirstName = "Sean";
oCust.Surname = "Connery";
ctx.Customers.Add(oCust);
ctx.SaveChanges();
}
}
Run the application a few times. Let's say so there are at least eight records in the database. We plan to change the record with the Id of 4 to Roger Moore. Below will show you how to fetch and amend a record using the CodeFirst technique.
static void Main(string[] args)
{
string sConn = "Data Source=<Your Server>;Initial Catalog=Shop;Integrated Security=True";
using (var ctx = new Shop(sConn))
{
Customer oCust = ctx.Customers.Find(3);
oCust.FirstName = "Roger";
oCust.Surname = "Moore";
ctx.Entry(oCust).CurrentValues.SetValues(oCust);
ctx.SaveChanges();
}
}
When you execute a select statement on the table, amongst the records of Sean Connery, there should be a Roger Moore record with an id of 3. Simple.. You might be able to devise a more efficient way, but this is the CodeFirst MVC way. The customer is the Model, and the Shop object is the Controller with which you would create the View. Another way to amend the record is to use the State property of the object if we know what the ID is and don't need to fetch it. In the example,. We are going to change the record with the ID of 5.
static void Main(string[] args)
{
string sConn = "Data Source=LAURANNE\\FISCELIA;Initial Catalog=Shop;Integrated Security=True";
using (var ctx = new Shop(sConn))
{
Customer oCust = new Customer();
oCust.CustomerID = 4;
oCust.FirstName = "Pierce";
oCust.Surname = "Brosnan";
ctx.Entry(oCust).State = System.Data.Entity.EntityState.Modified;
ctx.SaveChanges();
}
}
Notice the State. If we don't change the state to Modified, it will create a new record. When you select the records from the database, you will find that the id with four now has a customer called Pierce Brosnan.
Tags - Entity Framework
Last Modified : June 2023