Database Reference
In-Depth Information
{
order.PurchaseOrderId = Guid.NewGuid();
order.CreateDate = DateTime.UtcNow;
order.ModifiedDate = DateTime.UtcNow;
}
foreach (var order in changeSet.Where(c => c.State == System.Data.Entity.
EntityState.Modified).Select(a => a.Entity as PurchaseOrder))
{
order.ModifiedDate = DateTime.UtcNow;
}
}
return base.SaveChanges();
}
}
Following is the output from the code in Listing 12-7:
Purchase Orders
Purchase Order: 1b4df3c6-6f72-4c6b-9ce2-331bad509be5
Paid: No
Amount: $208.89
Created On: 3:15 PM
Modified at: 3:15 PM
Purchase Order: c042f045-38af-4bfc-93c0-a870ffd36195
Paid: No
Amount: $20.99
Created On: 3:15 PM
Modified at: 3:15 PM
Purchase Order: 223faf4a-e128-4f5a-8dee-b9b104ed43b7
Paid: No
Amount: $109.98
Created On: 3:15 PM
Modified at: 3:15 PM
How It Works
We demonstrated three different ways to set default values. For values that are static and for which a property is
exposed on the entity for the underlying column, we can use the designer's Default Value for the property. This is
ideally suited for the Paid property. By default, we want to set this to false . New purchase orders are typically unpaid.
For columns that need dynamically calculated values, such as the CreateDate, ModifiedDate, and
PurchaseOrderId columns, we override the Save Changes event that computes these values and sets the column values
just before the entity is saved to the database.
Finally, for columns that are not surfaced as properties on the entity and need a static default value, we can use
the Default Value attribute in the store layer property definition. In this recipe, we set the comments column default
value to “N/A” in the store layer property definition.
There is another option for assigning default values. You could assign them in the constructor for the entity.
The constructor is called each time a new instance of the entity is created. This includes each time the instance is
materialized from the database. You have to be careful not to overwrite previous values for the properties from
the database.
 
Search WWH ::




Custom Search