Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
dynamic obj = "";
if (model.LoadResultCount!=0)
{
obj = new LoadManagementResultsCountUserSetting();
obj.ResultsCount = Convert.ToInt16(model.LoadResultCount);
obj.Id = Convert.ToInt16(model.LoadResultCountId);
//var loadManagementResultCount = ApplicationService.GetSettings<LoadManagementResultsCountUserSetting>(f => f.Id == model.LoadResultCountId).FirstOrDefault();
//ApplicationService.Remove(loadManagementResultCount);
SaveResultCountUserSettings(obj, model);
}
if (model.PlanningResultCount!=0)
{
obj = new PlanningManagementResultsCountUserSetting();
obj.ResultsCount = Convert.ToInt16(model.PlanningResultCount);
obj.Id = Convert.ToInt16(model.PlanningResultCountId);
//var planningManagementResultCount = ApplicationService.GetSettings<PlanningManagementResultsCountUserSetting>().Where(f => f.Id == model.PlanningResultCountId).FirstOrDefault();
//ApplicationService.Remove(planningManagementResultCount);
SaveResultCountUserSettings(obj, model);
}
private void SaveResultCountUserSettings(dynamic obj, ResultCountViewModel model)
{
obj.IsEnabled = true;
obj.IsPrimary = model.IsPrimary;
obj.StartDate = DateTime.UtcNow;
obj.ModifiedDate = DateTime.UtcNow;
obj.ModifiedBy = AuthenticatedUser;
ApplicationService.Save(obj);
}
public void Save(BaseLogixSetting setting)
{
if (setting != null)
{
if (setting.Id > 0)
SettingsRepository.Attach(setting);
else
SettingsRepository.Add(setting);
Commit();
}
}
Related
I have looked through many examples of creating an audit trail using the Entity Framework and have yet to find anything that works for me. There must be a slick/terse way to do it by simply overriding SaveChanges in the DB Context and using the ChangeTracker...issues I have run into are things such as when adding (creating) an entity it does not have an ID until after you save it and when you save it, it seems to blast what's in the change tracker. Anyway, I have got an audit trail working but it's ugly as hell and I was looking for help in simplifying this and making it such that I don't have to add on to a horrible if-then every time I add an entity! Any and all help appreciated.
public bool CreateRecord(object o)
{
Audit audit = new Audit()
{
ChangeTypeID = (int)Audit.ChangeType.CREATE,
TimeStamp = GetCurrentDateTime(),
RecordClass = o.GetType().ToString(),
NewValue = "",
ReasonForChange = "Record Creation"
};
if (o.GetType() == typeof(Permission))
{
Permission x = (Permission)o;
audit.OriginalValue = x.ToString();
Permissions.Add(x);
SaveChanges();
audit.RecordID = x.ID;
}
else if (o.GetType() == typeof(User))
{
User x = (User)o;
audit.OriginalValue = x.ToString();
Users.Add(x);
SaveChanges();
audit.RecordID = x.ID;
}
else if (o.GetType() == typeof(LogIn))
{
LogIn x = (LogIn)o;
audit.OriginalValue = x.ToString();
LogIns.Add(x);
SaveChanges();
audit.RecordID = x.ID;
}
else if (o.GetType() == typeof(Marker))
{
Marker x = (Marker)o;
audit.OriginalValue = x.ToString();
Markers.Add(x);
SaveChanges();
audit.RecordID = x.ID;
}
else if (o.GetType() == typeof(Method))
{
Method x = (Method)o;
audit.OriginalValue = x.ToString();
Methods.Add(x);
SaveChanges();
audit.RecordID = x.ID;
}
else if (o.GetType() == typeof(Sample))
{
Sample x = (Sample)o;
audit.OriginalValue = x.ToString();
Samples.Add(x);
SaveChanges();
audit.RecordID = x.ID;
}
else if (o.GetType() == typeof(Run))
{
Run x = (Run)o;
audit.OriginalValue = x.ToString();
Runs.Add(x);
SaveChanges();
audit.RecordID = x.ID;
}
else if (o.GetType() == typeof(XYDataSet))
{
XYDataSet x = (XYDataSet)o;
audit.OriginalValue = x.ToString();
XYDataSets.Add(x);
SaveChanges();
audit.RecordID = x.ID;
}
else
{
return false;
}
// Save audit record
audit.UserID = ((App)Application.Current).GetCurrentUserID();
Audits.Add(audit);
SaveChanges();
return true;
}
I am assuming that all of the entities belongs to same project/assembly, so you can try something like that and notice that this code doesn't tested, modifications might be needed.
public bool CreateRecord(object o)
{
Audit audit = new Audit()
{
ChangeTypeID = (int)Audit.ChangeType.CREATE,
TimeStamp = GetCurrentDateTime(),
RecordClass = o.GetType().ToString(),
NewValue = "",
ReasonForChange = "Record Creation"
};
var entityType = Assembly.GetAssembly(typeof(Permission)).GetTypes().Where(x => x == o.GetType())
.FirstOrDefault(); // Determine the desired entity (assumed all of the entities belongs to same project/assembly)
if (entityType != null)
{
var convertedObject = Convert.ChangeType(o, entityType); // Convert object to entity
audit.OriginalValue = convertedObject.ToString();
var entity = yourContext.Set(entityType).Add(convertedObject); // Get DbSet for casted entity
SaveChanges();
audit.RecordID = x.ID;
}
else
{
return false;
}
// Save audit record
audit.UserID = ((App)Application.Current).GetCurrentUserID();
Audits.Add(audit);
SaveChanges();
return true;
}
I check if the record exists. The modelInit variable gets modelInit.Count = 0 when there is no record. I tried to save without checking if the record exists and threw the same exception.
Source
public void IncluiModeloIniciativa(ModeloIniciativaAuxiliar model)
{
ValidateEmptyFields(model);
int idIniciativa = model.IdIniciativa;
int idModelo = model.IdModelo;
List<ModeloIniciativa> modelInit = context.ModelosIniciativas
.Where(x => x.IdIniciativa == idIniciativa && x.IdModelo == idModelo).ToList();
if (null != modelInit && modelInit.Count > 0)
{
throw new ValidationException(
Resources.ModeloIniciativaResources.ModeloIniciativaJaExiste);
}
try
{
context.ModelosIniciativas.Add(new ModeloIniciativa()
{
IdIniciativa = model.IdIniciativa,
IdModelo = model.IdModelo,
Status = model.StatusMake,
VLR_INICIATIVA = model.VlrIniciativaMake.Value,
VLR_APROVADO = model.VlrAprovadoMake.Value,
VLR_SALDO = model.VlrSaldoMake.Value,
TipoIniciativa = TipoIniciativa.Make.ToString()
});
context.ModelosIniciativas.Add(new ModeloIniciativa()
{
IdIniciativa = model.IdIniciativa,
IdModelo = model.IdModelo,
Status = model.StatusBuy,
VLR_INICIATIVA = model.VlrIniciativaBuy.Value,
VLR_APROVADO = model.VlrAprovadoBuy.Value,
VLR_SALDO = model.VlrSaldoBuy.Value,
TipoIniciativa = TipoIniciativa.Buy.ToString()
});
context.ModelosIniciativas.Add(new ModeloIniciativa()
{
IdIniciativa = model.IdIniciativa,
IdModelo = model.IdModelo,
Status = model.StatusRnD,
VLR_INICIATIVA = model.VlrIniciativaRnD.Value,
VLR_APROVADO = model.VlrAprovadoRnD.Value,
VLR_SALDO = model.VlrSaldoRnD.Value,
TipoIniciativa = TipoIniciativa.RnD.ToString()
});
context.ModelosIniciativas.Add(new ModeloIniciativa()
{
IdIniciativa = model.IdIniciativa,
IdModelo = model.IdModelo,
Status = model.StatusCodesign,
VLR_INICIATIVA = model.VlrIniciativaCodesign.Value,
VLR_APROVADO = model.VlrAprovadoCodesign.Value,
VLR_SALDO = model.VlrSaldoCodesign.Value,
TipoIniciativa = TipoIniciativa.Codesign.ToString()
});
context.SaveChanges();
}
catch (Exception ex)
{
throw ex;
}
}
[Edited]
public BHX.Application.Logs.Models.Entity GetOrCreateEntity(Type type)
{
var logEntidade = this.AuditionContext.Entities.SingleOrDefault(entidade => entidade.Name == type.FullName);
if (logEntidade == null)
{
//Se for um subsite, deve pegar o caminho do site principal considerando o caminho atĂ© a Ășltima barra.
string caminhoSitePrincipal = System.AppDomain.CurrentDomain.BaseDirectory;
logEntidade = this.AuditionContext.Entities.Create();
logEntidade.Name = type.FullName;
logEntidade.AssemblyPath = #"bin\" + type.Assembly.ManifestModule.ToString();
this.AuditionContext.Entities.Add(logEntidade);
}
return logEntidade;
}
Stack Trace:
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
at BHX.ClienteGroup.eProgram.DataAccess.ECContext.GetOrCreateEntity(Type type) in C:\Projetos RTC\e-Program\W130_PRINCIPAL\03 - implementacao\aplicativo\web\DataAccess\ECContext.Auditing.cs:line 113
at BHX.ClienteGroup.eProgram.DataAccess.ECContext.saveEntryOperation(DbEntityEntry item, EntityState state) in C:\Projetos RTC\e-Program\W130_PRINCIPAL\03 - implementacao\aplicativo\web\DataAccess\ECContext.Auditing.cs:line 99
at BHX.ClienteGroup.eProgram.DataAccess.ECContext.SavePrograms(Boolean auditing) in C:\Projetos RTC\e-Program\W130_PRINCIPAL\03 - implementacao\aplicativo\web\DataAccess\ECContext.Auditing.cs:line 72
at BHX.ClienteGroup.eProgram.DataAccess.ECContext.SavePrograms() in C:\Projetos RTC\e-Program\W130_PRINCIPAL\03 - implementacao\aplicativo\web\DataAccess\ECContext.Auditing.cs:line 35
at BHX.ClienteGroup.eProgram.Services.ModeloIniciativaServices.IncluiModeloIniciativa(ModeloIniciativaAuxiliar model) in C:\Projetos RTC\e-Program\W130_PRINCIPAL\03 - implementacao\aplicativo\web\Services\ModeloIniciativaServices.cs:line 204
Every time you use Single or SingleOrDefault for a table and the result is more than one element, then will throw this exception. See the cell that the SaveChanges in ECContext is customized to save audit logs. Check how it saves these logs, why should not have a single key or not this checking the registry existence and saving more than once. You may not be using the custom method correctly.
I want to get the custom attributes, mentioned below, in breeze dataService (client side).
namespace Tam.Framework.Web.Models
{
[ViewAttribute("app/views/Employee.html")]//this custom class attribute
public class Employee : BaseEntity
{
protected override string OnGetDescriptor()
{
return "some description";
}
public string FirstName { get; set; }
[Display(Name = "LAST NAME")]//this custom property attribute
public string LastName { get; set; }
}
}
On the server, add logic to the Metadata controller action to supplement the standard metadata with the display attribute properties:
[HttpGet]
public virtual string Metadata()
{
// Extend metadata with extra attributes
var metadata = JObject.Parse(this.ContextProvider.Metadata());
var ns = metadata["schema"]["namespace"].ToString();
foreach (var breezeEntityType in metadata["schema"]["entityType"])
{
var typeName = ns + "." + breezeEntityType["name"].ToString();
var entityType = BuildManager.GetType(typeName, true);
foreach (var propertyInfo in entityType.GetProperties())
{
var attributes = propertyInfo.GetAllAttributes();
var breezePropertyInfo = breezeEntityType["property"].SingleOrDefault(p => p["name"].ToString() == propertyInfo.Name);
if (breezePropertyInfo == null)
continue;
// handle display attribute...
var displayAttribute = attributes.OfType<DisplayAttribute>().FirstOrDefault();
if (displayAttribute != null)
{
var displayName = displayAttribute.GetName();
if (displayName != null)
breezePropertyInfo["displayName"] = displayName;
var displayOrder = displayAttribute.GetOrder();
if (displayOrder != null)
breezePropertyInfo["displayOrder"] = displayOrder;
var autogenerateField = displayAttribute.GetAutoGenerateField();
if (autogenerateField != null)
breezePropertyInfo["autoGenerateField"] = autogenerateField;
}
// allowEmptyStrings.
if (propertyInfo.PropertyType == typeof(string))
{
breezePropertyInfo["allowEmptyStrings"] = true;
var requiredAttribute = attributes.OfType<RequiredAttribute>().FirstOrDefault();
if (requiredAttribute != null && !requiredAttribute.AllowEmptyStrings)
breezePropertyInfo["allowEmptyStrings"] = false;
}
// todo: handle other types of attributes...
}
}
return metadata.ToString();
}
On the client, fetch the metadata and supplement the breeze entity type with the custom metadata.
function initializeMetadataStore(metadataStore, metadata) {
var metadataType, metadataProperty, entityProperty, i, j;
for (i = 0; i < metadata.schema.entityType.length; i++) {
metadataType = metadata.schema.entityType[i];
var entityType = metadataStore.getEntityType(metadataType.name);
for (j = 0; j < metadataType.property.length; j++) {
metadataProperty = metadataType.property[j];
entityProperty = entityType.getProperty(metadataProperty.name);
if (entityProperty) {
if (typeof metadataProperty.displayName !== 'undefined') {
entityProperty.displayName = metadataProperty.displayName;
}
if (typeof metadataProperty.displayOrder !== 'undefined') {
entityProperty.displayOrder = metadataProperty.displayOrder;
}
if (typeof metadataProperty.autoGenerateField !== 'undefined') {
entityProperty.autoGenerateField = metadataProperty.autoGenerateField;
}
if (typeof metadataProperty.allowEmptyStrings !== 'undefined') {
entityProperty.allowEmptyStrings = metadataProperty.allowEmptyStrings;
}
}
}
}
}
var entityManager = ....something...;
entityManager.fetchMetadata(function (metadata) {
return initializeMetadataStore(entityManager.metadataStore, metadata);
});
now the additional metadata is available in the breeze entity type...
var propertyDisplayName = myEntity.entityType.getProperty('lastName').displayName;
var manager = configureBreezeManager();
function configureBreezeManager() {
breeze.NamingConvention.camelCase.setAsDefault();
var mgr = new breeze.EntityManager('api/breeze');
model.configureMetadataStore(mgr.metadataStore);
mgr.fetchMetadata(function (metadata) {
return initializeMetadataStore(mgr.metadataStore, metadata);
});
return mgr;
};
function initializeMetadataStore(metadataStore, metadata) {
breeze.NamingConvention.defaultInstance = breeze.NamingConvention.none;
var metadataType, metadataProperty, entityProperty, i, j;
for (i = 0; i < metadata.schema.entityType.length; i++) {
metadataType = metadata.schema.entityType[i];
var entityType = metadataStore.getEntityType(metadataType.name);
for (j = 0; j < metadataType.property.length; j++) {
metadataProperty = metadataType.property[j];
entityProperty = entityType.getProperty(metadataProperty.name);
if (entityProperty) {
if (typeof metadataProperty.displayName !== 'undefined') {
entityProperty.displayName = metadataProperty.displayName;
}
if (typeof metadataProperty.displayOrder !== 'undefined') {
entityProperty.displayOrder = metadataProperty.displayOrder;
}
if (typeof metadataProperty.autoGenerateField !== 'undefined') {
entityProperty.autoGenerateField = metadataProperty.autoGenerateField;
}
if (typeof metadataProperty.allowEmptyStrings !== 'undefined') {
entityProperty.allowEmptyStrings = metadataProperty.allowEmptyStrings;
}
}
}
}
}
var readData = function (entityName, observableResults, showLog) {
if (!entityName || !observableResults)
return null;
var query = new breeze.EntityQuery()
.from(entityName);
return manager.executeQuery(query)
.then(querySucceeded)
.fail(queryFailed);
}
function readEmployee() {
return breezeDataService.readData("Employees", employees, true).then(function () {
var propertyDisplayName = employees()[0].entityType.getProperty('lastName').displayName;//error displayName undefined
}
}
when I get list of entity by readData function that list (observableResults[0]) have not any displayName but I add displayName and checked it by initializeMetadataStore function is correct
FINALLY!!!!! I found it it because of breeze.NamingConvention.camelCase.setAsDefault();
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);
}
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.