update with entity framework self tracking entities - c#

I'm having a problem that I thought was easy to resolve.
This is my scenario (Entity framework 4 disconnected entities using self tracking).
Let's say I have 2 entities: Users, Orders.
From an asp.net page a get from the database 1 user and 1 order.
const int userId = 1;
const int orderId = 1;
var userManager = new UserManager();
var orderManager = new OrderManager();
var user = userManager.GetUser(userId);
var order = channelManager.GetChannel(channelId);
user.Orders.Add(order);
Now I need to create a function that updates the user adding the order to it.
I wrote something like:
public bool UpdateUser(User user)
{
context.AttachTo("Users", user);
var stateMgr = context.ObjectStateManager;
var stateEntry = stateMgr.GetObjectStateEntry(user);
for (int i = 0; i < stateEntry.CurrentValues.FieldCount; i++)
{
bool isKey = false;
string name = stateEntry.CurrentValues.GetName(i);
foreach (var keyPair in stateEntry.EntityKey.EntityKeyValues)
{
if (string.Compare(name, keyPair.Key, true) == 0)
{
isKey = true;
break;
}
}
if (!isKey)
{
stateEntry.SetModifiedProperty(name);
}
}
context.ApplyCurrentValues("Users", user);
return context.SaveChanges() > 0;
}
I don't have any error on this function and debugging everything seems to be ok, but when I check on the database the entity is not updated as expected.
I thought update a disconnected entity was something simple but apparently is not.
Can someone explaing me the logic between the update the entire graph of disconnected object with EF4? Please if you can I need to undestand the logic and not have a collection of links to look at. I already spent some time looking on internet but I'm finding so many approches that I'm not sure which one is correct.
Thanks

I don't see anything related to Self tracking entities in your code. Anyway STEs with ASP.NET don't work very well.
What is your code supposed to do? It looks like you want to do this:
public bool UpdateUser(User user)
{
context.AttachTo("Users", user);
context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
return context.SaveChanges() > 0;
}
But it will not save relations. I just answered some related question about working with detached graphs.

With Self Tracking Entities you have to use the ApplyChanges() method to sync the change on a context instead (and not attach).
The applychanges will go to the graph to update the linked object/collection.
Public Function UpdateEntity(entity As Entity) As Entity
Using dbContext As New EntityContext()
dbContext.EntitySet.ApplyChanges(entity)
dbContext.SaveChanges()
dbContext.Refresh(Objects.RefreshMode.StoreWins, entity)
End Using
Return entity
End Function
The refresh is optionnal, it is here only to push back the last value of the database. By the way the refresh doesn't update the linked object.

Related

EF Core upsert child entities upon parent entity save

I have a DDD aggregate with User as root and Appointment as the child records. I want, when I save a User in my repository, the existing child appointments of the User are updated and the child appointment which do not exist in the database be inserted.
I have for each entity a domain class and a persistence class
I have read this post on the matter and I think I understand what the accepted answer explained, so I went with the following logic :
public async Task Update(IApplicationUserWithAppointments domainUserEntity)
{
ApplicationUserEntity persistenceUserEntity = await FindEntityById(domainUserEntity.Id);
IDictionary<Guid, AppointmentEntity> appointmentEntitiesById =
persistenceUserEntity.Appointments
.ToDictionary(appointmentEntity => appointmentEntity.Id, appointmentEntity => appointmentEntity);
persistenceUserEntity.UserName = domainUserEntity.UserName;
persistenceUserEntity.Password = domainUserEntity.Password;
persistenceUserEntity.FirstName = domainUserEntity.FirstName;
persistenceUserEntity.LastName = domainUserEntity.LastName;
persistenceUserEntity.Role = domainUserEntity.Role;
persistenceUserEntity.Validated = domainUserEntity.Validated;
persistenceUserEntity.Appointments = domainUserEntity.Appointments
.Select(appointment => BuildOrUpdateAppointmentEntity(appointmentEntitiesById, appointment))
.ToList();
this.context.Users.Update(persistenceUserEntity);
}
private static AppointmentEntity BuildOrUpdateAppointmentEntity(IDictionary<Guid, AppointmentEntity> appointmentEntitiesById,
Appointment appointment)
{
if (!appointmentEntitiesById.ContainsKey(appointment.Id))
{
return new AppointmentEntity(appointment);
}
AppointmentEntity appointmentEntity = appointmentEntitiesById[appointment.Id];
appointmentEntity.State = appointment.State.Name;
appointmentEntity.DateTime = appointment.DateTime;
return appointmentEntity;
}
The logic is that I retrieve the user entity from the database with its appointments (to avoid detached entity error). Then, I map the appointment entity, updating those which exist and creating the new one.
This logic works well for the update of existing appointment records, but for the insertion of new appointments records, the following unit test fails :
public async Task Update_ChildRecord_InsertChildRecordInDb()
{
// Given
ApplicationUserEntity entity = await this.dbDataFactory.InsertValidatedLifeAssistant();
var repository = new ApplicationUserRepository(this.context, factory);
entity.Appointments.Add(new AppointmentEntity()
{
Id = Guid.NewGuid(),
State = "Planned",
DateTime = DateTime.Today.AddDays(3)
});
// When
await repository.Update(entity.ToDomainEntity(new AppointmentStateFactory()));
await repository.Save();
// Then
entity = await this.context
.Users
.Include(u => u.Appointments)
.FirstAsync(item => item.Id == entity.Id);
(await this.context.Appointments.CountAsync()).Should().Be(1);
}
With the following error :
The database operation was expected to affect 1 row(s), but actually affected 0 row(s); data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
On the Save call of the update.
I don't understand why my logic is not working. Thank you in advance
After a lot of debugging, and thank to a github post I realised that my problem was that my child record had already an Id generated, and EF Core did not expected it to. I solved my problem with by using ValueGeneratedNever() in my onModelCreating model definition. Ex :
modelBuilder.Entity<AppointmentEntity>().HasKey(appointment => appointment.Id);
modelBuilder.Entity<AppointmentEntity>().Property(appointment => appointment.Id).ValueGeneratedNever();
modelBuilder.Entity<AppointmentEntity>().Property(appointment => appointment.State);
modelBuilder.Entity<AppointmentEntity>().Property(appointment => appointment.DateTime);

EF5 can not handle Concurrency when Updating selective fields

I am using EF5 and Data First approach to Update entities.
I am using approach suggested by other questions to conditionally update only modified properties in the Entities.
Oki so here's the scenario My controller call Service with POCO objects and gets POCO objects from Service, The Service layer talks with Data layer which internally uses EF5 to retrieve entity from DB and Update them in DB.
The View data is loaded by controller from DTO object retrieved from Service layer.
User makes changes to View and Posts back JSON data to controller which gets mapped to DTO object in controller (courtesy MVC).
The controller makes call to Service layer with the DTO object (POCO) object.
The Service maps the POCO object to EF entity object and calls the Data layer's(i.e Repository) Update method passing in the EF entity.
In the Repository I fetch the existing entity from DB and call ApplyCurrentvaluesValues method, then I check if any properties are modified .
If properties are modified then I apply my custom logic to other entities which are not related to current entity and also Update the "UpdatedAdminId" & "UpdationDate" of current entity.
Post this I call "SaveChanges" method on Centext.
Every thing above I mentioned is working fine , except if I insert a break point in "SaveChanges" call and update some field modified by User to different value then "DbUpdateConcurrencyException" is not thrown by EF5.
i.e. I can get conditional Update & fire my custom logic when properties of my interest are modified to work perfectly.
But I am not getting error in case of the concurrency i.e the EF is not raising "DbUpdateConcurrencyException" in case a record is updated in between me fetching the record from DB , updating the record and saving it.
In real scenario there is a offline cron running which checks for newly created campaign and creates portfolio for them and marks the IsPortfolioCreated property below as true, in the mean time user can edit the campaign and the flag can be set to false even though the cron has created the portfolios.
To replicate the concurrency scenario I put a break point on SaveChanges and then Update the IsPortfolioCreated feild from MS-Sql enterprise manager for the same entity, but the "DbUpdateConcurrencyException" is not thrown even though the Data in Store has been updated.
Here's my code for reference,
Public bool EditGeneralSettings(CampaignDefinition campaignDefinition)
{
var success = false;
//campaignDefinition.UpdatedAdminId is updated in controller by retreiving it from RquestContext, so no its not comgin from client
var updatedAdminId = campaignDefinition.UpdatedAdminId;
var updationDate = DateTime.UtcNow;
CmsContext context = null;
GlobalMasterContext globalMasterContext = null;
try
{
context = new CmsContext(SaveTimeout);
var contextCampaign = context.CampaignDefinitions.Where(x => x.CampaignId == campaignDefinition.CampaignId).First();
//Always use this fields from Server, no matter what comes from client
campaignDefinition.CreationDate = contextCampaign.CreationDate;
campaignDefinition.UpdatedAdminId = contextCampaign.UpdatedAdminId;
campaignDefinition.UpdationDate = contextCampaign.UpdationDate;
campaignDefinition.AdminId = contextCampaign.AdminId;
campaignDefinition.AutoDecision = contextCampaign.AutoDecision;
campaignDefinition.CampaignCode = contextCampaign.CampaignCode;
campaignDefinition.IsPortfolioCreated = contextCampaign.IsPortfolioCreated;
var campaignNameChanged = contextCampaign.CampaignName != campaignDefinition.CampaignName;
// Will be used in the below if condition....
var originalSkeForwardingDomain = contextCampaign.skeForwardingDomain.ToLower();
var originalMgForwardingDomain = contextCampaign.mgForwardingDomain.ToLower();
//This also not firing concurreny exception....
var key = ((IObjectContextAdapter) context).ObjectContext.CreateEntityKey("CampaignDefinitions", campaignDefinition);
((IObjectContextAdapter)context).ObjectContext.AttachTo("CampaignDefinitions", contextCampaign);
var updated = ((IObjectContextAdapter)context).ObjectContext.ApplyCurrentValues(key.EntitySetName, campaignDefinition);
ObjectStateEntry entry = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetObjectStateEntry(updated);
var modifiedProperties = entry.GetModifiedProperties();
//Even tried this , works fine but no Concurrency exception
//var entry = context.Entry(contextCampaign);
//entry.CurrentValues.SetValues(campaignDefinition);
//var modifiedProperties = entry.CurrentValues.PropertyNames.Where(propertyName => entry.Property(propertyName).IsModified).ToList();
// If any fields modified then only set Updation fields
if (modifiedProperties.Count() > 0)
{
campaignDefinition.UpdatedAdminId = updatedAdminId;
campaignDefinition.UpdationDate = updationDate;
//entry.CurrentValues.SetValues(campaignDefinition);
updated = ((IObjectContextAdapter)context).ObjectContext.ApplyCurrentValues(key.EntitySetName, campaignDefinition);
//Also perform some custom logic in other entities... Then call save changes
context.SaveChanges();
//If campaign name changed call a SP in different DB..
if (campaignNameChanged)
{
globalMasterContext = new GlobalMasterContext(SaveTimeout);
globalMasterContext.Rename_CMS_Campaign(campaignDefinition.CampaignId, updatedAdminId);
globalMasterContext.SaveChanges();
}
}
success = true;
}
catch (DbUpdateConcurrencyException ex)
{
//Code never enters here, if it does then I am planning to show the user the values from DB and ask him to retry
//In short Store Wins Strategy
//Code in this block is not complete so dont Stackies don't start commenting about this section and plague the question...
// Get the current entity values and the values in the database
var entry = ex.Entries.Single();
var currentValues = entry.CurrentValues;
var databaseValues = entry.GetDatabaseValues();
// Choose an initial set of resolved values. In this case we
// make the default be the values currently in the database.
var resolvedValues = databaseValues.Clone();
// Update the original values with the database values and
// the current values with whatever the user choose.
entry.OriginalValues.SetValues(databaseValues);
entry.CurrentValues.SetValues(resolvedValues);
}
catch (Exception ex)
{
if (ex.InnerException != null)
throw ex.InnerException;
throw;
}
finally
{
if (context != null) context.Dispose();
if (globalMasterContext != null) globalMasterContext.Dispose();
}
return success;
}
Entity framework it's not doing anything special about concurrency until you (as developer) configure it to check for concurrency problems.
You are trying to catch DbUpdateConcurrencyException, the documentation for this exception says: "Exception thrown by DbContext when it was expected that SaveChanges for an entity would result in a database update but in fact no rows in the database were affected. ", you can read it here
In a database first approach, you have to set the property 'Concurrency Mode' for column on 'Fixed' (the default is None). Look at this screenshot:
The column Version is a SQL SERVER TIMESTAMP type, a special type that is automatically updated every time the row changes, read about it here.
With this configuration, you can try with this simple test if all is working as expected:
try
{
using (var outerContext = new testEntities())
{
var outerCust1 = outerContext.Customer.FirstOrDefault(x => x.Id == 1);
outerCust1.Description += "modified by outer context";
using (var innerContext = new testEntities())
{
var innerCust1 = innerContext.Customer.FirstOrDefault(x => x.Id == 1);
innerCust1.Description += "modified by inner context";
innerContext.SaveChanges();
}
outerContext.SaveChanges();
}
}
catch (DbUpdateConcurrencyException ext)
{
Console.WriteLine(ext.Message);
}
In the example above the update from the inner context will be committed, the update from the outer context will thrown a DbUpdateConcurrencyException, because EF will try to update the entity using 2 columns as a filters: the Id AND the Version column.
Hope this helps!

Add or Update a Record?

I have an MVC application with the following code in the POST method of the controller. I am doing an EF Add and obviously that is not right. I want it to add the record if it doesn't exist, otherwise Update. How can I do that please?
try
{
AttributeEntities db = new AttributeEntities();
IEnumerable<string> items = viewModel.SelectedAttributes2;
int i = 0;
foreach (var item in items)
{
var temp = item;
// Save it
SelectedHarmonyAttribute attribute = new SelectedHarmonyAttribute();
attribute.CustomLabel = viewModel.ItemCaptionText;
attribute.IsVisible = viewModel.Isselected;
string harmonyAttributeID = item.Substring(1, 1);
// attribute.OrderNumber = Convert.ToInt32(order);
attribute.OrderNumber = i++;
attribute.HarmonyAttribute_ID = Convert.ToInt32(harmonyAttributeID);
db.SelectedHarmonyAttributes.Add(attribute);
db.SaveChanges();
}
}
You would need to check the database for the record you are trying to add/update. If the look-up returns null, that means that it doesn't exist in the database. If it does, you can modify the record that you looked up and call db.SaveChanges() to persist the changes you made to the database.
Edit:
int id = Convert.ToInt32(harmonyAttributeID);
var existingEntry = db.SelectedHarmonyAttributes.SingleOrDefault(x => x.HarmonyAttribute_ID == id);
One common way to determine an add or update is by simply looking at an identifier field, and setting the appropriate state.
using System.Data;
SelectedHarmonyAttribute attribute;
using (var db = new YourDbContext())
{
db.Entry(attribute).State = attribute.HarmonyAttribute_ID == 0 ? EntityState.Added : EntityState.Modified;
db.SaveChanges();
}
You could import the System.Data.Entity.Migrations namespace and use the AddOrUpdate extension method:
db.SelectedHarmonyAttributes.AddOrUpdate(attribute);
db.SaveChanges();
EDIT:
I'm assuming that SelectedHarmonyAttributes is of type DbSet
EDIT2:
Only drawback with doing it this way (and it may not be a concern for you), is that your entity isn't responsible for it's own state change. This means that you can update any property of the entity to something invalid, where you might want to internally validate it on the entity itself or maybe do some other processing you always want to occur on update. If these things are a concern for you, you should add a public Update method onto the entity and check for its existence on the database first. e.g:
var attribute = db.SelectedHarmonyAttributes.SingleOrDefault(x => x.HarmonyAttribute_ID == harmonyAttributeID);
if (attribute != null)
{
attribute.Update(viewModel.ItemCaptionText, viewModel.Isselected, i++);
}
else
{
attribute = new Attribute(viewModel.ItemCaptionText, viewModel.Isselected);
db.SelectedHarmonyAttributes.Add(attribute);
}
db.SaveChanges();
Your update method might look something like:
public void Update(string customLabel, bool isVisible, int orderNumber)
{
if (!MyValidationMethod())
{
throw new MyCustomException();
}
CustomLabel = customLabel;
IsVisible = isVisible;
OrderNumber = orderNumber;
PerformMyAdditionalProcessingThatIAlwaysWantToHappen();
}
Then make all of the entities' properties public "get" but protected "set" so they can't be updated from outside the entity itself. This might be going off an a bit of a tangent but using the AddOrUpdate method would assume you don't want to control the way an update occurs and protect your domain entity from getting into an invalid state etc. Hope this helps!

Update database via Linq to SQL not working

I'm developing a C# ASP.NET application, in which i'm retrieving some data from the database, throwing in a form, and when i click on Save, i want it to save my changes in the database.
I'm using Linq to SQL. The code below, at the end, call the method ClienteBusiness.SalvarAlteracoes(cliente), which by the way, only calls the ClienteData.SalvarAlteracoes(cliente) method.
protected void Salvar()
{
TB_CLIENTE_CLI cliente = new TB_CLIENTE_CLI();
int idEstado = 0;
int idCidade = 0;
if (!Int32.TryParse(ddlEstado.SelectedValue, out idEstado))
{
return;
}
if (!Int32.TryParse(Request.Form[ddlCidade.UniqueID], out idCidade))
{
return;
}
cliente.TXT_RAZAOSOCIAL_CLI = txtRazaoSocial.Text;
cliente.TXT_NOMEFANTASIA_CLI = txtNomeFantasia.Text;
cliente.TXT_CNPJ_CLI = txtCNPJ.Text;
cliente.TXT_CEP_CLI = txtCEP.Text;
/*e os demais campos*/
//Se a tela for de edição, altera o valor do ID para o cliente correspondente.
cliente.ID_CLIENTE_CLI = this.IdCliente;
ClienteBusiness.SalvarAlteracoes(cliente);
HTMLHelper.jsAlertAndRedirect(this, "Salvo com sucesso!", ResolveUrl("~/Pages/ClientePage.aspx"));
}
The method which save the changes is described below:
public static Int32 SalvarAlteracoes(TB_CLIENTE_CLI cliente)
{
using (PlanoTesteDataContext context = DataContext.ObterConexao())
{
if (cliente.ID_CLIENTE_CLI == 0)
{
context.TB_CLIENTE_CLIs.InsertOnSubmit(cliente);
}
else
{
context.TB_CLIENTE_CLIs.Attach(cliente, true);
}
context.SubmitChanges();
} return cliente.ID_CLIENTE_CLI;
}
On the line context.TB_CLIENTE_CLIs.Attach(cliente, true); i'm receiving a System.InvalidOperationException: An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.
I've already checked the UpdateChecks and they are set to Never.
What can I do? Thanks and sorry for the bad english.
This should work:
else
{
context.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, cliente);
context.TB_CLIENTE_CLIs.Attach(cliente);
}
This Refresh overload will keep the changes made by the user,it compares the modified entity with the original values from the database, detects the difference and marks the entity as modified and the call to SubmitChanges applies the update to the database.
You may very well run into trouble using Linq2SQL with disconnected entities. EF is a more suited solution to handle this.
However, please ensure you have set all properties on the entity on UpdateCheck to NEVER. I have tested this myself and it works. If this does work it will run an UPDATE statement on every column regardless of whether it has been updated or not. Could cause a problem if you use triggers on your tables. It might be a better idea to use a Timestamp instead to track the entities so concurrency issues between multiple users can be raised.
If you try to Attach an entity from a context where the ObjectTrackingEnabled is not set to False then you will have the following exception thrown:
An unhandled exception of type 'System.NotSupportedException' occurred in System.Data.Linq.dll
Additional information: An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.
As an example please use the following for retrieving and reattaching an entity:
public TB_CLIENTE_CLI Get(int id)
{
using (PlanoTesteDataContext ctx = new PlanoTesteDataContext())
{
ctx.ObjectTrackingEnabled = false;
return ctx.TB_CLIENTE_CLI.SingleOrDefault(n => n.ID == id);
}
}
public void Save(TB_CLIENTE_CLI cliente)
{
using (PlanoTesteDataContext ctx = new PlanoTesteDataContext())
{
ctx.DeferredLoadingEnabled = false;
ctx.TB_CLIENTE_CLI.Attach(cliente, true);
ctx.SubmitChanges();
}
}
You will also need to set DeferredLoadingEnabled loading to False in the Save method so that you can save down changes on the entity subsequent times after the first initial save on modification.

What is a good way to perform updates with WCF Data Services (Odata)?

I am trying to devise a good way to perform updates to a SQL Server database using WCF Data Services and Entity Framework. The problem I'm having is that it seems overly complex to perform update, delete, and insert operations using the service.
I'll use typical Customer / Invoices scenario to help explain my current approach. I'm using WPF MVVM for the application. My view model contains a customer object that receives updates from the user. When saving, I pass the customer object to the service. The service must then load the customer object, transfer the property values from the updated customer, then perform the save.
Something like this:
public static int SaveProgram(Customer entity)
int returnValue = 0;
// Setup the service Uri
Uri serviceUri = new Uri(Properties.Settings.Default.DataUri);
try
{
// Get the DB context
var context = new DevEntities(serviceUri);
Customer dbCustomer;
if (entity.CustomerId == 0)
{
dbCustomer = new Customer();
context.AddToCustomers(dbCustomer);
}
else
{
dbCustomer = context.Customers.Where(p => p.CustomerId == entity.CustomerId).FirstOrDefault();
}
if (dbCustomer != null)
{
dbCustomer.StatusId = entity.StatusId;
dbCustomer.FirstName = entity.FirstName;
dbCustomer.LastName = entity.LastName;
dbCustomer.Address = entity.Address;
...
}
context.UpdateObject(dbCustomer);
// Submit Changes
DataServiceResponse response = context.SaveChanges(SaveChangesOptions.Batch);
// Check for errors
...
returnValue = response.Count();
}
... Catch exceptions
return returnValue;
}
Is it really necessary to go through all of this? It seems there should be an easier way.
Adding an invoice requires something like this:
var newInvoice = Invoice.CreateInvoice(0, customerId, etc...);
context.AddRelatedObject(dbCustomer, "Invoices", newInvoice);
Having already added a new invoice to the Customer.Invoices collection, this seems cumbersome.
Deleting an invoice is even worse. To delete an invoice I have to compare the invoices collection from the database with that of the passed in entity. If I cannot find a database version of the invoice in the entity.Invoices collection, then I know it should be deleted.
I have the feeling that I must not be approaching this correctly.

Categories