Entity Framework, change read-only column

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 (varchar 255), which has a unique key.

In the past, the value in this column was determined by the end users providing its value in the web form. The value has been verified by other users in the database to ensure a unique value before submitting the form.

The requirements have changed so that now this column value should be calculated at the first order creation and will never be changed later. The calculation includes counting the number of existing orders that have a VariableNumber field (varchar 255) with the same value. For instance:

int count = this.Orders.Where(o => o.VariableNumber == variableNumber).Count(); ++count; return string.Format("{0}-{1:000}", variableNumber, count); 

My question is: where do I put this logic to ensure that the Name is calculated when the order is first created?

Thanks.

+4
source share
1 answer

One approach does this in a database trigger. Another approach does this when overriding 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(); } } 
+1
source

Source: https://habr.com/ru/post/1347955/


All Articles