Entity Framework Original Value not as expected - entity-framework

In the following code I expect the Original Value to be different to the new value that I have set.
Why does my test fail? I am using EF 6.1.0
The Original Value is being incorrectly set to the new value.
[TestMethod]
public void CheckOriginalAndNew()
{
var dbContext = new ProjectContext();
var proj = dbContext.Projects.Find( 1);
proj.Description = Guid.NewGuid().ToString();
DbSet<Project> dbSet = dbContext.Set<Project>();
dbSet.Add(proj);
foreach (var entry in dbContext.ChangeTracker.Entries())
{
entry.State = System.Data.Entity.EntityState.Modified;
}
ObjectContext objectContex = ((IObjectContextAdapter)dbContext).ObjectContext;
objectContex.DetectChanges();
var entries =
objectContex.ObjectStateManager.GetObjectStateEntries(System.Data.Entity.EntityState.Modified);
foreach (ObjectStateEntry entry in entries.Where(e => e.Entity is LoggedEntity && !e.IsRelationship))
{
for (int i = 0; i < entry.CurrentValues.FieldCount; i++)
{
string fieldName = entry.CurrentValues.DataRecordInfo.FieldMetadata[i].FieldType.Name;
int ordinal = entry.OriginalValues.GetOrdinal(fieldName);
if (fieldName == "Description")
{
object newValue = entry.CurrentValues[ordinal];
object oldValue = entry.OriginalValues[ordinal];
Assert.AreNotEqual(newValue, oldValue); // fails! Why?
}
}
}
}

The reason the original value matches the current value is that the entry has been added instead of modified.
Instead of
DbSet<Project> dbSet = dbContext.Set<Project>();
dbSet.Add(proj);
I should have used
dbContext.Entry(proj).State = System.Data.Entity.EntityState.Modified;

Related

Open Xml - File Needs To Be Repaired To Open

I am having an issue where the file generation process works as expected, but when I open the excel file it says that it is corrupt and needs to be repaired. When the repair is complete, the file opens and all of the data is there.
The error message that I am receiving is as follows:
Removed Records: Cell information from /xl/worksheets/sheet1.xml part
My code is as follows:
using (var workbookDocument = SpreadsheetDocument.Create(staging, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
var count = query.Count();
var worksheetNumber = 1;
var worksheetCapacity = Convert.ToInt32(100000);
var worksheetCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(count) / worksheetCapacity));
var workbookPart = workbookDocument.AddWorkbookPart();
var worksheetInfo = new List<WorksheetData>();
OpenXmlWriter worksheetWriter;
while (worksheetNumber <= worksheetCount)
{
var worksheetLine = 1;
var worksheetName = sheet + "_" + Convert.ToString(worksheetNumber);
var worksheetPart = workbookDocument.WorkbookPart.AddNewPart<WorksheetPart>
var worksheetId = workbookDocument.WorkbookPart.GetIdOfPart(worksheetPart);
var worksheetKey = Convert.ToUInt32(worksheetNumber);
var worksheetAttributes = new List<OpenXmlAttribute>();
worksheetAttributes.Add(new OpenXmlAttribute("r", null, worksheetLine.ToString()));
worksheetInfo.Add(new WorksheetData() { Id = worksheetId, Key = worksheetKey, Name = worksheetName });
worksheetWriter = OpenXmlWriter.Create(worksheetPart);
worksheetWriter.WriteStartElement(new Worksheet());
worksheetWriter.WriteStartElement(new SheetData());
worksheetWriter.WriteStartElement(new Row(), worksheetAttributes);
for (var i = 0; i < headers.Count; i++)
{
var worksheetCell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
var worksheetValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(headers[i]);
worksheetAttributes.Clear();
worksheetAttributes.Add(new OpenXmlAttribute("t", null, "str"));
worksheetAttributes.Add(new OpenXmlAttribute("r", null, GetColumnReference(worksheetLine, i)));
worksheetWriter.WriteStartElement(worksheetCell, worksheetAttributes);
worksheetWriter.WriteElement(worksheetValue);
worksheetWriter.WriteEndElement();
}
worksheetWriter.WriteEndElement();
worksheetLine++;
var skip = ((worksheetNumber - 1) * worksheetCapacity);
var results = query.SelectProperties(columns).Skip(skip).Take(worksheetCapacity).ToList();
for (var j = 0; j < results.Count; j++)
{
worksheetAttributes.Clear();
worksheetAttributes.Add(new OpenXmlAttribute("r", null, worksheetLine.ToString()));
worksheetWriter.WriteStartElement(new Row());
for (var k = 0; k < columns.Count(); k++)
{
var column = columns[k].Split((".").ToCharArray()).Last();
var value = results[j].GetType().GetField(column).GetValue(results[j]);
var type = value?.GetType().Name;
var text = ExportFormatter.Format(type, value);
worksheetAttributes.Clear();
worksheetAttributes.Add(new OpenXmlAttribute("t", null, "str"));
worksheetAttributes.Add(new OpenXmlAttribute("r", null, GetColumnReference(worksheetLine, j)));
worksheetWriter.WriteStartElement(new Cell());
worksheetWriter.WriteElement(new CellValue(text));
worksheetWriter.WriteEndElement();
}
worksheetWriter.WriteEndElement();
worksheetLine++;
}
worksheetWriter.WriteEndElement();
worksheetWriter.WriteEndElement();
worksheetWriter.Close();
worksheetNumber++;
}
worksheetWriter = OpenXmlWriter.Create(workbookDocument.WorkbookPart);
worksheetWriter.WriteStartElement(new Workbook());
worksheetWriter.WriteStartElement(new Sheets());
for (var i = 0; i < worksheetInfo.Count; i++)
{
worksheetWriter.WriteElement(new Sheet()
{
Name = worksheetInfo[i].Name,
SheetId = worksheetInfo[i].Key,
Id = worksheetInfo[i].Id
});
}
worksheetWriter.WriteEndElement();
worksheetWriter.WriteEndElement();
worksheetWriter.Close();
}
I use the below class to track the worksheet information:
private class WorksheetData
{
public String Id { get; set; }
public UInt32 Key { get; set; }
public String Name { get; set; }
}
Can anyone identify why this is happening?
Perhaps and extra ending tag or ones that missing?
Finally got this to work, there were a few issues.
The cell references A1 A2 A3, etc... were not correct in the code.
The row number were not beign tracked corretly.
The attributes being applied to the cell elements were not correct because they wern't being cleared prior to writing.
The usage of the CallValue was not functioning as expected. Not sure exactly why, but when the Cell Value is used it doesn't open properly in excel. Simply using the cell and setting the DataType and CellValue properties did work. Note - The underlying xml looked exactly the same between the two, but only the second worked.
The final code from this is as follows:
public static ExportInfo Export<T>(this IQueryable<T> query, String temp, String path, List<ExportField> fields)
{
var worker = new ExportWorker();
return worker.Export<T>(query, temp, path, fields);
}
public static class ExportFormatter
{
public static String Format(String type, Object value)
{
if (value == null)
{
return "";
}
else
{
var text = "";
switch (type)
{
case "Decimal":
var decimalValue = (Decimal)value;
text = decimal.Round(decimalValue, 2, MidpointRounding.AwayFromZero).ToString();
break;
case "DateTimeOffset":
var dateTimeOffset = (DateTimeOffset)value;
text = dateTimeOffset.ToUniversalTime().ToString("MM/dd/yyyy");
break;
case "DateTime":
var dateTime = (DateTime)value;
text = dateTime.ToUniversalTime().ToString("MM/dd/yyyy");
break;
default:
text = Convert.ToString(value);
break;
}
return text;
}
public class ExportWorker
{
String record;
String staging;
String destination;
Thread thread;
Timer timer;
public ExportInfo Export<T>(IQueryable<T> query, String temp, String path, List<ExportField> fields)
{
var selections = from a in fields group a by new { a.Field } into g select new { g.Key.Field, Header = g.Max(x => x.Header) };
var headers = (from a in selections select a.Header).ToList();
var columns = (from a in selections select a.Field).Distinct().ToList();
var entity = query.ElementType.ToString();
var array = entity.Split((".").ToCharArray());
var sheet = array[array.Length - 1];
var key = Guid.NewGuid().ToString().Replace("-", "_");
var name = key + ".xlsx";
var log = key + ".txt";
var timeout = 60 * 60000;
staging = temp + name;
destination = path + name;
record = path + log;
thread = new Thread(
new ThreadStart(() =>
{
try
{
using (var workbookDocument = SpreadsheetDocument.Create(staging, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
var count = query.Count();
var worksheetNumber = 1;
var worksheetCapacity = Convert.ToInt32(100000);
var worksheetCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(count) / worksheetCapacity));
var workbookPart = workbookDocument.AddWorkbookPart();
var worksheetInfo = new List<WorksheetData>();
OpenXmlWriter worksheetWriter;
while (worksheetNumber <= worksheetCount)
{
var worksheetLine = 1;
var worksheetThrottle = 0;
var worksheetName = sheet + "_" + Convert.ToString(worksheetNumber);
var worksheetPart = workbookDocument.WorkbookPart.AddNewPart<WorksheetPart>();
var worksheetId = workbookDocument.WorkbookPart.GetIdOfPart(worksheetPart);
var worksheetKey = Convert.ToUInt32(worksheetNumber);
var worksheetAttributes = new List<OpenXmlAttribute>();
worksheetAttributes.Add(new OpenXmlAttribute("r", null, worksheetLine.ToString()));
worksheetInfo.Add(new WorksheetData() { Id = worksheetId, Key = worksheetKey, Name = worksheetName });
worksheetWriter = OpenXmlWriter.Create(worksheetPart);
worksheetWriter.WriteStartElement(new Worksheet());
worksheetWriter.WriteStartElement(new SheetData());
worksheetWriter.WriteStartElement(new Row(), worksheetAttributes);
for (var i = 0; i < headers.Count; i++)
{
var worksheetCell = new Cell();
worksheetCell.DataType = CellValues.String;
worksheetCell.CellValue = new CellValue(headers[i]);
worksheetWriter.WriteElement(worksheetCell);
worksheetAttributes.Clear();
}
worksheetWriter.WriteEndElement();
worksheetLine++;
var skip = ((worksheetNumber - 1) * worksheetCapacity);
var results = query.SelectProperties(columns).Skip(skip).Take(worksheetCapacity).ToList();
for (var j = 0; j < results.Count; j++)
{
if (worksheetThrottle >= 5) { worksheetThrottle = 0; System.Threading.Thread.Sleep(1); }
worksheetAttributes.Clear();
worksheetAttributes.Add(new OpenXmlAttribute("r", null, worksheetLine.ToString()));
worksheetWriter.WriteStartElement(new Row(), worksheetAttributes);
for (var k = 0; k < columns.Count(); k++)
{
var column = columns[k].Split((".").ToCharArray()).Last();
var value = results[j].GetType().GetField(column).GetValue(results[j]);
var type = value?.GetType().Name;
var text = (String)ExportFormatter.Format(type, value);
var worksheetCell = new Cell();
worksheetCell.DataType = CellValues.String;
worksheetCell.CellValue = new CellValue(text);
worksheetWriter.WriteElement(worksheetCell);
worksheetAttributes.Clear();
}
worksheetWriter.WriteEndElement();
worksheetLine++;
worksheetThrottle++;
}
worksheetWriter.WriteEndElement();
worksheetWriter.WriteEndElement();
worksheetWriter.Close();
worksheetNumber++;
}
worksheetWriter = OpenXmlWriter.Create(workbookDocument.WorkbookPart);
worksheetWriter.WriteStartElement(new Workbook());
worksheetWriter.WriteStartElement(new Sheets());
for (var i = 0; i < worksheetInfo.Count; i++)
{
worksheetWriter.WriteElement(new Sheet()
{
Name = worksheetInfo[i].Name,
SheetId = worksheetInfo[i].Key,
Id = worksheetInfo[i].Id
});
}
worksheetWriter.WriteEndElement();
worksheetWriter.WriteEndElement();
worksheetWriter.Close();
}
var logsfile = File.CreateText(record);
var datafile = (new DirectoryInfo(temp)).GetFiles().FirstOrDefault(a => a.Name == name);
datafile.MoveTo(destination);
logsfile.WriteLine("succeeded");
logsfile.Close();
}
catch (Exception ex)
{
try { File.Delete(staging); } catch (Exception) { }
var logsfile = File.CreateText(record);
logsfile.WriteLine("failed");
logsfile.WriteLine(ex.ToString());
logsfile.Close();
}
})
);
thread.Start();
timer = new Timer(Expire, null, timeout, Timeout.Infinite);
return new ExportInfo() { File = destination, Log = record };
}
void Expire(object state)
{
try { File.Delete(staging); } catch (Exception) { }
var logsfile = File.CreateText(record);
logsfile.WriteLine("timeout");
logsfile.Close();
thread.Abort();
}
private class WorksheetData
{
public String Id { get; set; }
public UInt32 Key { get; set; }
public String Name { get; set; }
}
}
After making those adjustments, the export works beautifully.
Also, open xml solved a lot of problems that I was having with memory management.
Using the above approach allowed me to export 3 files, each with 1.5 million rows (40 columns) in about 10 minutes.
During the export process, CPU utilization never exceeded 35% and it never used more than 1/10 of a gig of memory. Bravo...

ef core 2 apply HasQueryFilter for all entity

Is there any way to apply "HasQueryFilter" globaly to all my entity ? I don't want
to add in modelbuilder one by one ?
modelBuilder.Entity<Manufacturer>().HasQueryFilter(p => p.IsActive);
In case you have base class or interface defining the IsActive property, you could use the approach from Filter all queries (trying to achieve soft delete).
Otherwise you could iterate entity types, and for each type having bool IsActive property build dynamically filter expression using Expression class methods:
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
var isActiveProperty = entityType.FindProperty("IsActive");
if (isActiveProperty != null && isActiveProperty.ClrType == typeof(bool))
{
var parameter = Expression.Parameter(entityType.ClrType, "p");
var filter = Expression.Lambda(Expression.Property(parameter, isActiveProperty.PropertyInfo), parameter);
entityType.QueryFilter = filter;
}
}
Update (EF Core 3.0): Due to public metadata API breaking change (replacing many properties with Get / Set extension methods), the last line becomes
entityType.SetQueryFilter(filter);
For those looking to implement Ivan's answer in EF Core 3.0, note the necessary change in the last line:
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
var isActiveProperty = entityType.FindProperty("IsActive");
if (isActiveProperty != null && isActiveProperty.ClrType == typeof(bool))
{
var parameter = Expression.Parameter(entityType.ClrType, "p");
var filter = Expression.Lambda(Expression.Property(parameter, isActiveProperty.PropertyInfo), parameter);
MutableEntityTypeExtensions.SetQueryFilter(entityType, filter);
}
}
Here is extention method for EF Core version 6
public static void ApplySoftDeleteQueryFilter(this ModelBuilder modelBuilder)
{
var entityTypes = modelBuilder.Model
.GetEntityTypes();
foreach (var entityType in entityTypes)
{
var isActiveProperty = entityType.FindProperty("IsActive");
if (isActiveProperty != null && isActiveProperty.ClrType == typeof(bool))
{
var entityBuilder = modelBuilder.Entity(entityType.ClrType);
var parameter = Expression.Parameter(entityType.ClrType, "e");
var methodInfo = typeof(EF).GetMethod(nameof(EF.Property))!.MakeGenericMethod(typeof(bool))!;
var efPropertyCall = Expression.Call(null, methodInfo, parameter, Expression.Constant("IsActive"));
var body = Expression.MakeBinary(ExpressionType.Equal, efPropertyCall, Expression.Constant(true));
var expression = Expression.Lambda(body, parameter);
entityBuilder.HasQueryFilter(expression);
}
}
}

Entity Framework - how to save entity without saving related objects

In my Entity Framework, I have three related entities 'Client', 'ClientAddress' and 'LookupAddressType'. "LookupAddressType" is a master class specifying the type of available address type, like business address, residential address etc. ClientAddress depend on LookupAddresstype and Client. While saving a Client entity with relevant ClientAddress data, i'm getting following error.
"Violation of PRIMARY KEY constraint 'PK_LookupAddressType'. Cannot
insert duplicate key in object 'dbo.LookupAddressType'. The statement
has been terminated.
I do not need LookupAddressType to be inserted. Here I just need the relevant lookupAddressTypeId to be inserted in clientAddress entity.
The Saving code is like this:
Add(Client);
_objectContext.SaveChanges();
how can i do this?
The Load Code is below:
private void LoadClientDetails(EFEntities.Client _Client)
{
EFEntities.LookupClientStatu clientStatus;
var clientAddressList = new List<ClientAddress>();
if (_Client == null)
{
return;
}
//Assign data to client object
_Client.ClientName = rtxtName.Text;
_Client.Alias = rtxtAlias.Text;
_Client.ClientCode =Int32.Parse(rtxtClientCode.Text);
_Client.TaxPayerID = rtxtTaxPayerId.Text;
if (rcboStatus.SelectedIndex != 0)
{
clientStatus = new EFEntities.LookupClientStatu
{
ClientStatusID = (Guid) (rcboStatus.SelectedValue),
ClientStatusDescription = rcboStatus.Text
};
_Client.LookupClientStatu = clientStatus;
}
//_Client.Modified = EnvironmentClass.ModifiedUserInstance.Id;
_Client.EffectiveDate = rdtEffectiveDate.Value;
if (rdtExpDate.Value != rdtExpDate.MinDate)
{
_Client.ExpirationDate = rdtExpDate.Value;
}
else
{
_Client.ExpirationDate = null;
}
_Client.StartDate = DateTime.Now;
EFEntities.ClientAddress clientAddress = null;
// Iesi.Collections.Generic.ISet<ClientAddress> clientAddress = new HashedSet<ClientAddress>();
foreach (var cAddress in _clientController.client.ClientAddresses)
{
clientAddress = cAddress;
break;
}
if (clientAddress == null)
{
clientAddress = new EFEntities.ClientAddress();
}
clientAddress.Address1 = rtxtClientAdd1.Text;
clientAddress.Address2 = rtxtClientAdd2.Text;
clientAddress.Address3 = rtxtClientAdd3.Text;
// Address type details
if (rcboClientAddType.SelectedIndex != -1)
{
clientAddress.LookupAddressType = new EFEntities.LookupAddressType
{
AddressTypeID = (Guid) (rcboClientAddType.SelectedValue),
AddressTypeDescription = rcboClientAddType.Text
};
//clientAddress.AddressType.Id = Convert.ToByte(rcboClientAddType.SelectedValue);
}
clientAddress.City = rtxtClientCity.Text;
clientAddress.Client = _Client;
\
_Client.ClientAddresses.Add(clientAddress);
}
Well I did this to the following lines of code to make it work.
if (rcboClientAddType.SelectedIndex != -1)
{
clientAddress.LookupAddressType = new EFEntities.LookupAddressType
{
AddressTypeID = (Guid) (rcboClientAddType.SelectedValue),
AddressTypeDescription = rcboClientAddType.Text
};
//clientAddress.AddressType.Id = Convert.ToByte(rcboClientAddType.SelectedValue);
}
I changed the above code into this
if (rcboClientAddType.SelectedIndex != -1)
{
//clientAddress.LookupAddressType = new EFEntities.LookupAddressType
// {
// AddressTypeID = (Guid) (rcboClientAddType.SelectedValue),
// AddressTypeDescription = rcboClientAddType.Text
// };
clientAddress.AddressTypeID = (Guid)(rcboClientAddType.SelectedValue);
}

Merge Self-tracking entities

Graph of objects stored in the database and the same object graph is serialized into a binary package. Package is transmitted over the network to the client, then it is necessary to merge data from the package and data from the database.
Source code of merge:
//objList - data from package
var objectIds = objList.Select(row => row.ObjectId).ToArray();
//result - data from Database
var result = SomeService.Instance.LoadObjects(objectIds);
foreach (var OSobj in objList)
{
var obj = result.Objects.ContainsKey(OSobj.ObjectId)
? result.Objects[OSobj.ObjectId]
: result.Objects.CreateNew(OSobj.ObjectId);
var targetObject = result.DataObjects.Where(x => x.ObjectId == OSobj.ObjectId).FirstOrDefault();
targetObject.StopTracking();
var importedProperties = ImportProperties(targetObject.Properties, OSobj.Properties);
targetObject.Properties.Clear();
foreach (var property in importedProperties)
{
targetObject.Properties.Add(property);
}
targetObject.StartTracking();
}
return result;
And code of ImportProperties method:
static List<Properties> ImportProperties(
IEnumerable<Properties> targetProperties,
IEnumerable<Properties> sourceProperties)
{
Func<Guid, bool> hasElement = targetProperties
.ToDictionary(e => e.PropertyId, e => e)
.ContainsKey;
var tempTargetProperties = new List<Properties>();
foreach (var sourceProperty in sourceProperties)
{
if (!hasElement(sourceProperty.PropertyId))
{
sourceProperty.AcceptChanges();
tempTargetProperties.Add(sourceProperty.MarkAsAdded());
}
else
{
sourceProperty.AcceptChanges();
tempTargetProperties.Add(sourceProperty.MarkAsModified());
}
}
return tempTargetProperties;
}
Server save incoming changes like this :
_context.ApplyChanges("OSEntities.Objects", entity);
_context.SaveChanges(SaveOptions.DetectChangesBeforeSave);
When the server tries to save the changes occur exception:
AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.
But if I change the code of ImportProperties method, the error does not occur and the changes are saved successfully:
static List<Properties> ImportProperties(
IEnumerable<Properties> targetProperties,
IEnumerable<Properties> sourceProperties)
{
Func<Guid, bool> hasElement = targetProperties.ToDictionary(e => e.PropertyId, e => e).ContainsKey;
var tempTargetProperties = new List<Properties>();
foreach (var sourceProperty in sourceProperties)
{
if (!hasElement(sourceProperty.PropertyId))
{
var newProp = new Properties
{
ElementId = sourceProperty.ElementId,
Name = sourceProperty.Name,
ObjectId = sourceProperty.ObjectId,
PropertyId = sourceProperty.PropertyId,
Value = sourceProperty.Value
};
tempTargetProperties.Add(newProp);
}
else
{
var modifiedProp = new Properties
{
ElementId = sourceProperty.ElementId,
Name = sourceProperty.Name,
ObjectId = sourceProperty.ObjectId,
PropertyId = sourceProperty.PropertyId,
Value = sourceProperty.Value
};
modifiedProp.MarkAsModified();
tempTargetProperties.Add(modifiedProp);
}
}
return tempTargetProperties;
}
Why is there an exception?
When you transport an object graph (Entity with n-level deep navigation properties) to a client application the entities will record any changes made in their respective change trackers. When entity (or object graph) is sent back to the server side of the application basically all you need to do is:
try
{
using(Entities context = new Entities())
{
context.ApplyChanges(someEntity);
context.SaveChanges();
}
}
catch
{
...
}
I don't see the need of all the code above you posted. What are you trying to achieve with that code?

Entity Framework overwrites data when 2 two people save data simultaneously

In a function I pass a list of related values and loop over them to save changes in the database. All works well until 2 or more people use the same page to update different entities .Then only that data gets saved for which the changes were made more recently.
public bool UpdatePermanentDifferenceBL(List<PermanentDifferenceProperties> permDiffDetails)
{
try
{
int permanentDifferenceID=0;
int taxEntityID = 0;
int mapid = 0;
//using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
//{
Topaz.DAL.PermanentDifference permDiff;
for (int i = 0; i < permDiffDetails.Count; i++)
{
if ((bool)(HttpContext.Current.Session[GlobalConstant.currentDataSet]) == true && (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]) == 0)
{
using (var ctx = new TopazDbContainer())
{
try
{
permanentDifferenceID = permDiffDetails[i].PermanentDifferenceID;
taxEntityID = permDiffDetails[i].TaxEntityID;
mapid = permDiffDetails[i].MapID;
permDiff = new Topaz.DAL.PermanentDifference();
permDiff = ctx.PermanentDifference.Where(p => p.PermanentDifferenceID == permanentDifferenceID && p.TaxEntityID == taxEntityID && p.MapID == mapid).SingleOrDefault();
permDiff.Business = permDiffDetails[i].Business;
permDiff.Interest = permDiffDetails[i].Interest;
permDiff.Corporate = permDiffDetails[i].Corporate;
permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
permDiff.Total = permDiffDetails[i].Total;
permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
permDiff.ModifiedDate = DateTime.Now;
ctx.SaveChanges();
}
catch (System.Data.OptimisticConcurrencyException ex)
{
permanentDifferenceID = permDiffDetails[i].PermanentDifferenceID;
taxEntityID = permDiffDetails[i].TaxEntityID;
mapid = permDiffDetails[i].MapID;
permDiff = new Topaz.DAL.PermanentDifference();
ctx.Refresh(System.Data.Objects.RefreshMode.StoreWins, permDiff);
permDiff = ctx.PermanentDifference.Where(p => p.PermanentDifferenceID == permanentDifferenceID && p.TaxEntityID == taxEntityID && p.MapID == mapid).SingleOrDefault();
permDiff.Business = permDiffDetails[i].Business;
permDiff.Interest = permDiffDetails[i].Interest;
permDiff.Corporate = permDiffDetails[i].Corporate;
permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
permDiff.Total = permDiffDetails[i].Total;
permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
permDiff.ModifiedDate = DateTime.Now;
ctx.SaveChanges();
}
}
}
//ctx.ContextOptions.UseLegacyPreserveChangesBehavior = true;
}
//}
//using (UnitOfWork uow = new UnitOfWork())
//{
// for (int i = 0; i < permDiffDetails.Count; i++)
// {
// if ((bool)(HttpContext.Current.Session[GlobalConstant.currentDataSet]) == true && (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]) == 0)
// {
// Repository.PermanentDifferenceRepository pDiffRepo = new Repository.PermanentDifferenceRepository(uow);
// Topaz.DAL.PermanentDifference permDiff = pDiffRepo.GetByEntityId(permDiffDetails[i].PermanentDifferenceID, permDiffDetails[i].TaxEntityID, permDiffDetails[i].MapID);
// permDiff.Business = permDiffDetails[i].Business;
// permDiff.Interest = permDiffDetails[i].Interest;
// permDiff.Corporate = permDiffDetails[i].Corporate;
// permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
// permDiff.Total = permDiffDetails[i].Total;
// permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
// permDiff.ModifiedDate = DateTime.Now;
// pDiffRepo.ApplyChanges(permDiff);
// }
// else
// {
// int snapshotID = (int)(HttpContext.Current.Session[GlobalConstant.snapShotID]);
// SnapShotPermanentDifferenceRepository pDiffRepo = new SnapShotPermanentDifferenceRepository(uow);
// SnapShotPermanentDifference permDiff = pDiffRepo.GetByEntityId(permDiffDetails[i].PermanentDifferenceID, permDiffDetails[i].TaxEntityID, permDiffDetails[i].MapID,snapshotID);
// permDiff.SnapshotID = snapshotID;
// permDiff.Business = permDiffDetails[i].Business;
// permDiff.Interest = permDiffDetails[i].Interest;
// permDiff.Corporate = permDiffDetails[i].Corporate;
// permDiff.UnallocatedTax = permDiffDetails[i].UnallocatedTax;
// permDiff.Total = permDiffDetails[i].Total;
// permDiff.ModifiedBy = permDiffDetails[i].ModifiedBy;
// permDiff.ModifiedDate = DateTime.Now;
// pDiffRepo.ApplyChanges(permDiff);
// }
// }
// uow.SaveChanges();
return true;
}
catch (Exception ex)
{
TopazErrorLogs.AddTopazErrorLogBL(ex, 1, 1);
throw new TopazCustomException(GlobalConstant.errorMessage);
}
}
Any urgent assistance is much appreciated.
The common way to solve this is adding additional column to every table where you want to handle concurrency. This column will have ROWVERSION or TIMESTAMP data type. Once you map tables in EDMX you will get a new computed property of type byte[] and set its Concurrency mode to fixed. This setting will force EF to add additional WHERE condition to every UPDATE or DELETE statement validating that row version is the same as it was when the record was loaded from the database. If the row version is not the same (another thread updated the record) the record from modification is not found and you will get exception.
Database will change the value every time you update the record automatically. You just need to ensure that your entity uses the value which was retrieved when the entity was loaded from the database.
Apologies all the viewstate and to some extent session was the culprit and not EntityFramework.