Entity Framework, change column to Read-only
I am using .NET 4.0, Entity Framework 4, and SQL Server 2005.
I have an existing EF model. One of the Entities named Order has a column named Name (varc开发者_StackOverflow社区har 255) which has a unique key on it.
In the past the value in this column was determined by end users providing its value on a web form. The value was checked against others in the database to ensure a unique value before the form could be submitted.
Requirements have changed so that now this column's value is to be calculated the first time the Order is created, and never changed afterwards. The calculation involves counting the number of existing Orders that have a field VariableNumber (varchar 255) with the same value. For Example:
int count = this.Orders.Where(o => o.VariableNumber == variableNumber).Count();
++count;
return string.Format("{0}-{1:000}", variableNumber, count);
My question is this: where do I put this logic to ensure the Name is calculated when the Order is first created?
Thank You.
One approach is doing this in a database trigger. Another approach is doing this in overriden SaveChanges
:
public override void SaveChanges()
{
var orders = context.ObjectStateManager
.GetObjectStateEntries(EntityState.Added)
.Select(e => e.Entity)
.OfType<Order>();
if (orders.Count() > 0)
{
// serialized transaction to lock records so
// that concurrent thread can't insert orders
// with the same name while this threads preparing
// its orders
using (var scope = new TransactionScope())
{
// Here get current counts for variable numbers
foreach (var order in orders)
{
order.Name = ...;
}
base.SaveChanges();
scope.Complete();
}
}
else
{
// saving changes with default transaction
base.SaveChanges();
}
}
精彩评论