Database Reference
In-Depth Information
{
ItemId = itemId,
Name = "Xcel Camping Tent",
UnitPrice = 129.95M
};
var originalItem = context.Items.Where(x => x.ItemId == itemId).FirstOrDefault<Item>();
context.Entry(originalItem).CurrentValues.SetValues(item);
context.SaveChanges();
}
using (var context = new EFRecipesEntities())
{
var item = context.Items.Single();
Console.WriteLine("Item: {0}, UnitPrice: {1}", item.Name,
item.UnitPrice.ToString("C"));
}
}
}
public partial class Item
{
public int ItemId { get; set; }
public string Name { get; set; }
public decimal UnitPrice { get; set; }
}
public partial class EFRecipesEntities : DbContext
{
public EFRecipesEntities()
: base("name=EFRecipesEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Item> Items { get; set; }
}
The following is the output of the code in Listing 8-9:
Item: Xcel Camping Tent, UnitPrice: $99.95
Item: Xcel Camping Tent, UnitPrice: $129.95
How It Works
In Listing 8-9, we inserted an item into the model and saved it to the database. Then we pretended to receive an
updated item, perhaps from a Silverlight client.
Next we need to update the item in the database. To do this, we need to get the entity from the database into the
context. To get the entity, we used a Where clause with FirstorDefault and checked with the ID of the item. After
that, we used the Entry() method of the context, which enables access to entire entity to apply any methods on that
entity. Thus we used CurrentValues.SetValues to replace the original values with new values that come through the
client. Finally, SaveChanges is called on the DbContext.
 
Search WWH ::




Custom Search