I am working on a survey application with Asp.Net MVC.
I have a page named Index.cshtml which has a question table and a 'Add New' button.Once button clicked, a popup is opened with jQuery. I am calling a view from controller to fill jQuery dialog named as AddOrEdit.cshtml (child page). I am adding new question and options. Question is a textfield and its options are added in editable table. Once clicked submit button, Submit form event (save or update) is fired. My Question and its Options class has a one-to-many relatonship. EF6 tries to save parent entities with its child entities. But I want to save childs after insertion of parents not the same time. How can I handle this problem.
I am using DB First approach. What is the best practice?
Question.cs
namespace MerinosSurvey.Models
{
using System;
using System.Collections.Generic;
public partial class Questions
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Questions()
{
this.Responses = new HashSet<Responses>();
this.Options = new HashSet<Options>();
}
public int QuestionId { get; set; }
public string QuestionName { get; set; }
public int QuestionTypeId { get; set; }
public System.DateTime CreatedDate { get; set; }
public int CreatedUserId { get; set; }
public bool IsActive { get; set; }
public bool Status { get; set; }
public System.DateTime UpdatedDate { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Responses> Responses { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Options> Options { get; set; }
}
}
Option.cs
namespace MerinosSurvey.Models
{
using System;
using System.Collections.Generic;
public partial class Options
{
public int OptionId { get; set; }
public string OptionName { get; set; }
public int QuestionId { get; set; }
public System.DateTime CreatedDate { get; set; }
public System.DateTime UpdatedDate { get; set; }
public bool IsActive { get; set; }
public bool Status { get; set; }
public virtual Questions Questions { get; set; }
}
}
QuestionController.cs - AddOrEdit Action
[HttpPost]
public ActionResult AddOrEdit(Questions question)
{
if (question != null)
{
using (MerinosSurveyEntities db = new MerinosSurveyEntities())
{
Questions questionComing = db.Questions.FirstOrDefault(x => x.QuestionId == question.QuestionId);
if (questionComing != null)
{
//Update
questionComing.QuestionName = question.QuestionName;
questionComing.Status = true;
questionComing.IsActive = true;
questionComing.UpdatedDate = DateTime.Now;
db.Questions.Attach(questionComing);
db.Entry(questionComing).State = EntityState.Modified;
question.QuestionId = questionComing.QuestionId;
db.SaveChanges();
}
else
{
//New Question
question.Status = true;
question.IsActive = true;
question.UpdatedDate = DateTime.Now;
question.CreatedDate = DateTime.Now;
db.Questions.Attach(question);
db.Entry(question).State = EntityState.Added;
db.SaveChanges();
question.QuestionId = question.QuestionId;
}
List<Options> options = question.Options.ToList();
List<Options> existingOptions = new List<Options>(db.Options.Where(x =>
x.Status && x.IsActive && x.QuestionId == question.QuestionId));
foreach (Options existingOption in existingOptions)
{
Options optionUpdated = options.FirstOrDefault(x => x.OptionId == existingOption.OptionId);
if (optionUpdated != null)
{
//Update
existingOption.UpdatedDate = DateTime.Now;
existingOption.OptionName = optionUpdated.OptionName;
existingOption.IsActive = true;
existingOption.Status = true;
db.Options.Attach(existingOption);
db.Entry(existingOption).State = EntityState.Modified;
db.SaveChanges();
options.RemoveAll(x => x.OptionId == existingOption.OptionId);
}
else
{
//Delete
existingOption.Status = false;
existingOption.UpdatedDate = DateTime.Now;
db.Options.Attach(existingOption);
db.Entry(existingOption).State = EntityState.Modified;
db.SaveChanges();
}
}
foreach (Options optionNew in options)
{
optionNew.IsActive = true;
optionNew.Status = true;
optionNew.CreatedDate = DateTime.Now;
optionNew.UpdatedDate = DateTime.Now;
optionNew.QuestionId = question.QuestionId;
db.Options.Add(optionNew);
db.SaveChanges();
}
return Json(new { success = true, message = "Soru başarılı bir şekilde güncellendi."
},
JsonRequestBehavior.AllowGet);
}
}
return Json(new { success = true, message = "Bir problem oluştu." },
JsonRequestBehavior.AllowGet);
}
Your approach is very deliberate, but prone to problems. With EF, the DbContext acts much like a unit of work and SaveChanges should only ever be called once. With something like a related hierarchy where you have a Question with Options, you update and save the question, but then what happens if there is a problem with saving one of the options? You would be committing changes partially and leaving data in an incomplete, inaccurate state.
It's also a LOT of boilerplate code, some of it such as explicitly setting a tracked entity's state to Modified is completely unnecessary. The operation could be revised and simplified down to something like:
[HttpPost]
public ActionResult AddOrEdit(Questions question)
{
if (question == null) // Assert and fail. Avoids nesting.
return Json(new { success = true, message = "Bir problem oluştu." },
JsonRequestBehavior.AllowGet);
using (MerinosSurveyEntities db = new MerinosSurveyEntities())
{
Questions questionComing = db.Questions.Include(x => x.Options).SingleOrDefault(x => x.QuestionId == question.QuestionId); // Prefetch our options...
if (questionComing != null)
{ //Update
questionComing.QuestionName = question.QuestionName;
questionComing.Status = true;
questionComing.IsActive = true;
questionComing.UpdatedDate = DateTime.Now;
// db.Questions.Attach(questionComing); -- not needed, already tracked
// db.Entry(questionComing).State = EntityState.Modified; - Not needed
// question.QuestionId = questionComing.QuestionId; -- Redundant. The ID matches, we loaded based on it.
// db.SaveChanges(); -- No save yet.
// Handle options here... There are probably optimizations that can be added.
var activeOptionIds = question.Options.Where(x => x.Status && s.IsActive).Select(x => x.OptionId).ToList();
foreach(var option in question.Options.Where(x => activeOptionIds.Contains(x.OptionId))
{
var existingOption = questionComing.Options.SingleOrDefault(x => x.OptionId == option.OptionId);
if(existingOption != null)
{ // Update
existingOption.UpdatedDate = DateTime.Now;
existingOption.OptionName = optionUpdated.OptionName;
existingOption.IsActive = true;
existingOption.Status = true;
}
else
{ // New
questionComing.Options.Add(option); // Provided we trust the data coming in. Otherwise new up an option and copy over values.
}
}
var removedOptions = questionComing.Options.Where(x => !activeOptionIds.Contains(x.OptionId).ToList();
foreach(var option in removedOptions)
{
option.Status = option.IsActive = false;
option.UpdatedDate = DateTime.Now;
}
}
else
{ //New Question
// Dangerous to trust the Question coming in. Better to validate and copy values to a new Question to add...
question.Status = true;
question.IsActive = true;
question.UpdatedDate = question.CreatedDate = DateTime.Now;
// db.Questions.Attach(question); -- Add it...
// db.Entry(question).State = EntityState.Added;
// question.QuestionId = question.QuestionId; -- Does nothing...
db.Questions.Add(question); // This will append all Options as well.
}
// Now, after all changes are in, Save.
db.SaveChanges();
return Json(new { success = true, message = "Soru başarılı bir şekilde güncellendi." },JsonRequestBehavior.AllowGet);
} // end using.
}
This I would further break down into private methods to handle the add vs. update. While this doesn't answer how you can update a parent without it's children, it should demonstrate why you should leverage the capabilities of EF to ensure that children are updated with their parents properly. SaveChanges should only ever be called one time within the lifetime scope of a DbContext so that it ensures that all related changes are either committed or rolled back in the event of a failure. EF manages relationships between entities that it is told to track so you can add an entity with new children. Where you need to be careful is with references, such as if you have an existing QuestionType entity associated with a new question. In these scenarios you always want to load the entity within the DbContext scope and use that reference, not a detached reference coming in because EF will treat that as a new entity resulting in duplicate data or duplicate key constraints being hit. It's generally advisable to not pass entities between client and server to avoid issues like this. Attaching or adding entities coming from the client can expose a system to data tampering if not validated properly, and can lead to issues when it comes to referencing existing data.
For instance if you pass in a new question that has a QuestionType reference of "MultipleChoice" (A lookup table of question types) where that is QuestionType ID #1. If you do something like:
db.Questions.Add(question);
"question" was untracked, and all referenced entities are untracked. If you add it, or attach it as a new entity, those referenced entities will be treated as new entities. This would effectively want to Insert a new QuestionType ID #1, leading to a key violation (row already exists) or would insert a new QuestionType ID #12 for example if the QuestionType was configured for incrementing ID. To get around this:
var existingQuestionType = db.QuestionTypes.Single(x => x.QuestionTypeId == question.QuestionType.QuestionTypeId);
question.QuestionType = existingQuestionType; // Points our question type reference at the existing, tracked reference.
db.Questions.Add(question);
question.QuestionType and existingQuestionType would both have an ID of 1 in this example. The difference is that existingQuestionType is tracked/known by the Context where question.QuestionType was an untracked reference. If we added question without the context knowing about the reference, it would treat it like it would a child record of question and want to insert that too. This is probably one of the biggest things that trips people up with EF references and leads to problems and efforts to get more deliberate with related entities, but takes away a lot of the advantages EF can provide. We point our new question reference at the tracked entity so when EF goes to insert the question, it already knows the QuestionType reference as an existing row and everything works as expected.
As you can see below, I'm trying to update the "active" and "version" fields, which are properties of the templateData object.
When I want to add a new record, it works fine and meets the needs. But when I try to update the state.modified line, the error is:
Attaching an entity of type '...' failed because another entity already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
Although I have tried many ways of crashing (as you noticed) I have not been successful.
What is the cause of this error? And how can I handle it?
Thank you for your help.
Service:
public ResultObject<TemplateData> SaveTemplateData(TemplateData oTemplateData)
{
var oResult = new ResultObject<TemplateData>();
using (var contextTransaction = _context.Database.BeginTransaction())
{
try
{
var listTempDatas = _context.TemplateDatas.Where(td => td.TemplateRID == oTemplateData.TemplateRID)
.ToList();
#region active/version
oTemplateData.Active = true;
if (listTempDatas.Count > 0)
{
#region resetActives
listTempDatas.ForEach(ltd => ltd.Active = false);
#endregion
#region getMaxVersion
var maxVersionValue = listTempDatas.Max(ltd => ltd.TemplateVersion);
//var maxVersionValue2 = listTempDatas.OrderByDescending(ltd => ltd.TemplateVersion).Select(ltd => ltd.TemplateVersion).First();
oTemplateData.TemplateVersion = maxVersionValue + 1;
#endregion
}
else if (listTempDatas.Count == 0)
{
oTemplateData.TemplateVersion = 1;
}
#endregion
if (oTemplateData.ID > 0)
{
var oldTempData = _context.TemplateDatas.AsNoTracking()
.FirstOrDefault(td => td.ID == oTemplateData.ID);
if (oldTempData != null)
_context.Entry(oTemplateData).State = EntityState.Modified;// and there it is
}
else if (oTemplateData.ID == 0)
{
_context.Entry(oTemplateData).State = EntityState.Added;
}
_context.SaveChanges();
oResult.ResulObject = oTemplateData;
contextTransaction.Commit();
}
catch (Exception e)
{
contextTransaction.Rollback();
oResult.AddError("TemplateService.SaveTemplateData", e.ToString());
}
}
return oResult;
}
Entity:
public class TemplateData
{
...
public int ID { get; set; }
public int? TemplateRID { get; set; }
...
public int? TemplateVersion { get; set; }
public bool? Active { get; set; }
...
public virtual Template Template { get; set; }
}
DataContextExtension:
public static ApplicationDbContext BulkInsert<T>(this ApplicationDbContext context, T entity, int count,
int batchSize) where T : class
{
context.Set<T>().Add(entity);
if (count % batchSize == 0)
{
context.SaveChanges();
context.Dispose();
context = new ApplicationDbContext();
// This is optional
context.Configuration.AutoDetectChangesEnabled = false;
}
return context;
}
The problem is that the line
var listTempDatas = _context.TemplateDatas.Where(td => td.TemplateRID == oTemplateData.TemplateRID)
.ToList();
already loads (tracks) in the context the existing entity you are trying to update.
So first you can try to find it in that list (instead of with a separate database query):
var oldTempData = listTempDatas.FirstOrDefault(td => td.ID == oTemplateData.ID);
and then simply update the properties of the existing entity rather than trying to mark the detached entity as modified:
if (oldTempData != null)
_context.Entry(oldTempData).CurrentValues.SetValues(oTemplateData); // and there you go
I am trying to prevent any deletes on my database tables. Currently using Entity Framework 5. Firstly here is my code,
public override int SaveChanges()
{
var Changed = ChangeTracker.Entries();
if (Changed != null)
{
foreach (var entry in Changed.Where(e => e.State == EntityState.Deleted))
{
entry.State = EntityState.Unchanged;
}
}
return base.SaveChanges();
}
I've managed to prevent it with this way. When i use Remove method of EF its not working anymore.However, what i am trying to achieve is, when i use the remove method for the given ID, i want to set isDeleted(which is a (bit) column in all my db tables) value to false. Currently, i am lost in the documents and shared codes around the internet.
Thanks
I would probably handle this by making entities that are soft deletable implement an interface, something like ISoftDeletable.
public interface ISoftDeletable
{
bool IsDeleted { get; set; }
}
Then extend your code above to check if the entity type implements the ISoftDeletable interface, if it does simply set IsDeleted to true.
public override int SaveChanges()
{
var Changed = ChangeTracker.Entries();
if (Changed != null)
{
foreach (var entry in Changed.Where(e => e.State == EntityState.Deleted))
{
entry.State = EntityState.Unchanged;
if (entry.Entity is ISoftDeletable)
{
// Set IsDeleted....
}
}
}
return base.SaveChanges();
}
You would then need to make sure queries for the Entities that implement ISoftDeletable filter out those that are soft deleted.
Building on #BenjaminPauls great answer, but using the generic Entries<TEntity>. In my opinion it cleans up the code and the nestling a bit.
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries<ISoftDeletable>())
{
if (entry.State == EntityState.Deleted)
{
// Set deleted.
}
}
return base.SaveChanges();
}
Or even:
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries<ISoftDeletable>()
.Where(x => x.State == EntityState.Deleted)
{
// Set deleted.
}
return base.SaveChanges();
}
I'm trying to save an object graph of POCOs I have mapped to EF6 using Code First fluent notations.
Upon saving the object graph however, I stumble upon primary key violation exceptions.
The object graph is quite simple:
One Issue can contain multiple WorkItems with each one Author (as User).
The objects are populated externally (using a Web API)
When I attempt to save an issue with two workitems which refer to the same author, I would expect the issue to be inserted, the workitems to be inserted and one author to be inserted, and the other one to be referenced or be updated.
What happens however is that the issue is inserted, the workitems are inserted and both references to the same user are inserted, resulting in a primary key violation.
Simplified Issue object:
public class Issue
{
public Issue()
{
WorkItems = new List<WorkItem>();
}
public string Id { get; set; }
private List<WorkItem> _workItems;
public List<WorkItem> WorkItems
{
get { return _workItems ?? new List<WorkItem>(); }
set { _workItems = value; }
}
}
Simplified WorkItem:
public class WorkItem
{
public string Id { get; set; }
public string AuthorLogin
{
get; set;
}
private WorkItemAuthor _author;
public WorkItemAuthor Author
{
get { return _author; }
set { _author = value;
if (value != null)
{
AuthorLogin = value.Login;
}
else
{
AuthorLogin = string.Empty;
}
}
}
}
Simplified user object:
public class User
{
public string Login { get; set; }
public string FullName { get; set; }
}
Their Code-first configurations:
internal IssueConfiguration()
{
HasKey(x => x.Id);
HasMany(x => x.WorkItems);
}
internal WorkItemConfiguration()
{
HasKey(x => x.Id);
HasRequired(p => p.Author)
.WithMany(b => b.WorkItems)
.HasForeignKey(x=>x.AuthorLogin);
}
internal UsersConfiguration()
{
HasKey(x => x.Login);
}
All quite straightforward. Upon database create, de tables look fine and dandy too, with FKs on the columns where one would expect them
Now when saving the issue, it would have been nice if the object graph would be inserted, and the reference to existing objects would be recognized automagically and optionally inserted or referenced only.
I attempt to add issues accordingly:
using (var db = new Cache.Context())
{
if (db.Issues.Any(e => e.Id == issue.Id))
{
db.Issues.Attach(issue);
db.Entry(issue).State = EntityState.Modified;
}
else
{
db.Issues.Add(issue);
}
db.SaveChanges();
}
Is the solution to this issue that I walk through the object graph to manually add or attach the other objects in the graph too? I would expect by defining the proper Foreign Key values these references would be recognized.
I finally ended up doing something similar to this, quite laborious and I would still like to find a better way.
Finding out whether an entity is already attached or exists in the database turned out to be pollute the model too much (implementing IEquatable<T> is fine, but I think implementing IEntityWithKey on my POCOs pollutes the POCO too much. (and till that did not seem to suffice tracking entities in the context)
internal static void Save(this List<Issue> issues)
{
using (var db = new Context())
{
foreach (var issue in issues.ToList())
{
foreach (var workItem in issue.WorkItems.ToList())
{
if (workItem.Author != null)
{
var existing = db.Users.SingleOrDefault(e => e.Login == workItem.Author.Login);
if (existing == null)
{
db.Users.Add(workItem.Author);
}
else
{
//Update existing entities' properties
existing.Url = workItem.Author.Url;
//Replace reference
workItem.Author = existing;
}
db.SaveChanges();
}
var existingWorkItem = db.WorkItems.SingleOrDefault(e => e.Id == workItem.Id);
if (existingWorkItem == null)
{
db.WorkItems.Add(workItem);
}
else
{
//Update existing entities' properties
existingWorkItem.Duration = workItem.Duration;
//Replace reference
issue.WorkItems.Remove(workItem);
issue.WorkItems.Add(existingWorkItem);
}
db.SaveChanges();
}
var existingIssue = db.Issues.SingleOrDefault(x => x.Id == issue.Id);
if (existingIssue == null)
{
db.Issues.Add(issue);
}
else
{
//Update existing entities' properties
existingIssue.SpentTime = issue.SpentTime;
}
db.SaveChanges();
}
}
}
There is a small bug in the Issue object.
"return _workItems ?? new List();" could return a new WorkItem on every get if _workItems ever became null. Here is the fixed version.
public class Issue {
public Issue() {
WorkItems = new List<WorkItem>();
}
public String Id {
get; set;
}
public List<WorkItem> WorkItems { get; private set; }
}
Frustrating, this. Here's a pair of related objects, as generated by database-first Entity Framework:
public partial class DevelopmentType
{
public DevelopmentType()
{
this.DefaultCharges = new HashSet<DefaultCharge>();
}
public System.Guid RowId { get; set; }
public string Type { get; set; }
public virtual ICollection<DefaultCharge> DefaultCharges { get; set; }
}
public partial class DefaultCharge
{
public System.Guid RowId { get; set; }
public decimal ChargeableRate { get; set; }
public Nullable<System.Guid> DevelopmentType_RowId { get; set; }
public virtual DevelopmentType DevelopmentType { get; set; }
}
Here's the code that I'm calling to save a DevelopmentType - it involves automapper since we differentiate entity objects from DTOs:
public void SaveDevelopmentType(DevelopmentType_dto dt)
{
Entities.DevelopmentType mappedDevType = Mapper.Map<DevelopmentType_dto, Entities.DevelopmentType>(dt);
_Context.Entry(mappedDevType).State = System.Data.EntityState.Modified;
_Context.DevelopmentTypes.Attach(mappedDevType);
_Context.SaveChanges();
}
In my user interface, the most common operation will be for a user to look at a list of DevelopmentTypes and update their DefaultCharge. So when I test this using the above code, it runs without error, but nothing actually changes.
If I pause in the debugger it's clear that the changed DefaultCharge is being passed into the function, and that it's attached to the DevelopmentType to be saved.
Stepping through it, if I change the value manually inside visual studio, it does save the updated value. Which is just even more confusing.
Monitoring the database with SQL Server Profiler reveals that update commands are issued only for the parent object and not for any attached objects.
I have other similar code elsewhere that functions as expected. What am I doing wrong here?
EDIT:
I have discovered that if you do this prior to the call to SaveDevelopmentType:
using (TransactionScope scope = new TransactionScope())
{
dt.Type = "Test1";
dt.DefaultCharges.First().ChargeableRate = 99;
_CILRepository.SaveDevelopmentType(dt);
scope.Complete();
}
The change to Type saves, but the change to ChargeableRate does not. I don't think it helps, massively, but thought I'd add it.
The problem is, that EF is not aware of the changed DefaultCharges.
By setting the State of the DevelopmentType to EntityState.Modified, EF only knows that the object DevelopmentType has been changed. However, this means that EF will only update DevelopmentType but not it's navigation properties.
A workaround - which isn't best practice - would be to iterate over all DefaultCharge of the current DevelopmentType and set the entity state to EntityState.Modified.
Additionally I would recommend to attach the entity to the context first, and change the state afterwards.
EDIT after comment
As you are using DTOs I suppose you are transfering these objects either through different layers or different machines.
In this case I would recommend to use self tracking entities, because it is not possible to share one context. These entities additionally holds their current state (ie. new, updated, deleted etc). There are many tutorials on the net about self tracking entities.
e.g. MSDN - Working with Self-Tracking Entities
As far as I know EF can save child entities only if the parent object was retrieved with the same Context that is trying to save it. That is attaching an object that was retrieved by one context to another context, will allow you to save changes to parent objects but not children. This was the result of a on old search based on which we switched to NHibernate. If memory serves correctly I was able to find a link where EF team member(s) confirmed this and that there WAS no plan to change this behavior. Unfortunately all links related to that search have been erased from my PC since.
As I am not aware of how you are retrieving the objects in your case, I am not sure this is relevant to your case, but put it out there just in case it helps.
Here is a link on attaching detached objects to a context.
http://www.codeproject.com/Articles/576330/Attaching-detached-POCO-to-EF-DbContext-simple-and
Context.Entry() already "Attaches" the Entity internally in order to have the context change its EntityState.
By calling Attach() you're changing the EntityState back to Unchanged. Try to comment out this line.
The Graphdiff library was a great help for me to handle all of these complexities.
You only need to set up the navigation properties that you wish to insert/update/delete (using fluent syntax) and Graphdiff will take care of it
Note: It seems to be that the project is not updated anymore but i'm using it since more than a year and is quite stable
This is not a workaround for every case, but I did discover that you can get around this by updating foreign keys on an object instead of updating navigation property objects.
For example... instead of:
myObject.myProperty = anotherPropertyObject;
Try this:
myObject.myPropertyID = anotherPropertyObject.ID;
Make sure the object is flagged as modified in EF's mind (as mentioned in other posts) and then call your save method.
Worked for me at least! It'll be a no-go when working with nested properties, but perhaps you can break your contexts up into smaller chunks and work over objects in multiple parts to avoid context bloat.
Good luck! :)
If I understand the question correctly, you have problem updating child fields. I had problems with child collection fields. I tried this and it worked for me.
You should update all child collections after attaching the object to the database context change the modified state of the parent object and save changes to the context.
Database.Products.Attach(argProduct);
argProduct.Categories = Database.Categories.Where(x => ListCategories.Contains(x.CategoryId)).ToList();
Database.Entry(argProduct).State = EntityState.Modified;
Database.SaveChanges();
I created a helper method to solve this problem.
Consider this:
public abstract class BaseEntity
{
/// <summary>
/// The unique identifier for this BaseEntity.
/// </summary>
[Key]
public Guid Id { get; set; }
}
public class BaseEntityComparer : IEqualityComparer<BaseEntity>
{
public bool Equals(BaseEntity left, BaseEntity right)
{
if (ReferenceEquals(null, right)) { return false; }
return ReferenceEquals(left, right) || left.Id.Equals(right.Id);
}
public int GetHashCode(BaseEntity obj)
{
return obj.Id.GetHashCode();
}
}
public class Event : BaseEntity
{
[Required(AllowEmptyStrings = false)]
[StringLength(256)]
public string Name { get; set; }
public HashSet<Manager> Managers { get; set; }
}
public class Manager : BaseEntity
{
[Required(AllowEmptyStrings = false)]
[StringLength(256)]
public string Name { get; set; }
public Event Event{ get; set; }
}
DbContext with the helper method:
public class MyDataContext : DbContext
{
public MyDataContext() : base("ConnectionName") { }
//Tables
public DbSet<Event> Events { get; set; }
public DbSet<Manager> Managers { get; set; }
public async Task AddOrUpdate<T>(T entity, params string[] ignoreProperties) where T : BaseEntity
{
if (entity == null || Entry(entity).State == EntityState.Added || Entry(entity).State == EntityState.Modified) { return; }
var state = await Set<T>().AnyAsync(x => x.Id == entity.Id) ? EntityState.Modified : EntityState.Added;
Entry(entity).State = state;
var type = typeof(T);
RelationshipManager relationship;
var stateManager = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager;
if (stateManager.TryGetRelationshipManager(entity, out relationship))
{
foreach (var end in relationship.GetAllRelatedEnds())
{
var isForeignKey = end.GetType().GetProperty("IsForeignKey", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(end) as bool?;
var navigationProperty = end.GetType().GetProperty("NavigationProperty", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(end);
var propertyName = navigationProperty?.GetType().GetProperty("Identity", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(navigationProperty) as string;
if (string.IsNullOrWhiteSpace(propertyName) || ignoreProperties.Contains(propertyName)) { continue; }
var property = type.GetProperty(propertyName);
if (property == null) { continue; }
if (end is IEnumerable) { await UpdateChildrenInternal(entity, property, isForeignKey == true); }
else { await AddOrUpdateInternal(entity, property, ignoreProperties); }
}
}
if (state == EntityState.Modified)
{
Entry(entity).OriginalValues.SetValues(await Entry(entity).GetDatabaseValuesAsync());
Entry(entity).State = GetChangedProperties(Entry(entity)).Any() ? state : EntityState.Unchanged;
}
}
private async Task AddOrUpdateInternal<T>(T entity, PropertyInfo property, params string[] ignoreProperties)
{
var method = typeof(EasementDataContext).GetMethod("AddOrUpdate");
var generic = method.MakeGenericMethod(property.PropertyType);
await (Task)generic.Invoke(this, new[] { property.GetValue(entity), ignoreProperties });
}
private async Task UpdateChildrenInternal<T>(T entity, PropertyInfo property, bool isForeignKey)
{
var type = typeof(T);
var method = isForeignKey ? typeof(EasementDataContext).GetMethod("UpdateForeignChildren") : typeof(EasementDataContext).GetMethod("UpdateChildren");
var objType = property.PropertyType.GetGenericArguments()[0];
var enumerable = typeof(IEnumerable<>).MakeGenericType(objType);
var param = Expression.Parameter(type, "x");
var body = Expression.Property(param, property);
var lambda = Expression.Lambda(Expression.Convert(body, enumerable), property.Name, new[] { param });
var generic = method.MakeGenericMethod(type, objType);
await (Task)generic.Invoke(this, new object[] { entity, lambda, null });
}
public async Task UpdateForeignChildren<T, TProperty>(T parent, Expression<Func<T, IEnumerable<TProperty>>> childSelector, IEqualityComparer<TProperty> comparer = null) where T : BaseEntity where TProperty : BaseEntity
{
var children = (childSelector.Invoke(parent) ?? Enumerable.Empty<TProperty>()).ToList();
foreach (var child in children) { await AddOrUpdate(child); }
var existingChildren = await Set<T>().Where(x => x.Id == parent.Id).SelectMany(childSelector).AsNoTracking().ToListAsync();
if (comparer == null) { comparer = new BaseEntityComparer(); }
foreach (var child in existingChildren.Except(children, comparer)) { Entry(child).State = EntityState.Deleted; }
}
public async Task UpdateChildren<T, TProperty>(T parent, Expression<Func<T, IEnumerable<TProperty>>> childSelector, IEqualityComparer<TProperty> comparer = null) where T : BaseEntity where TProperty : BaseEntity
{
var stateManager = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager;
var currentChildren = childSelector.Invoke(parent) ?? Enumerable.Empty<TProperty>();
var existingChildren = await Set<T>().Where(x => x.Id == parent.Id).SelectMany(childSelector).AsNoTracking().ToListAsync();
if (comparer == null) { comparer = new BaseEntityComparer(); }
var addedChildren = currentChildren.Except(existingChildren, comparer).AsEnumerable();
var deletedChildren = existingChildren.Except(currentChildren, comparer).AsEnumerable();
foreach (var child in currentChildren) { await AddOrUpdate(child); }
foreach (var child in addedChildren) { stateManager.ChangeRelationshipState(parent, child, childSelector.Name, EntityState.Added); }
foreach (var child in deletedChildren)
{
Entry(child).State = EntityState.Unchanged;
stateManager.ChangeRelationshipState(parent, child, childSelector.Name, EntityState.Deleted);
}
}
public static IEnumerable<string> GetChangedProperties(DbEntityEntry dbEntry)
{
var propertyNames = dbEntry.State == EntityState.Added ? dbEntry.CurrentValues.PropertyNames : dbEntry.OriginalValues.PropertyNames;
foreach (var propertyName in propertyNames)
{
if (IsValueChanged(dbEntry, propertyName))
{
yield return propertyName;
}
}
}
private static bool IsValueChanged(DbEntityEntry dbEntry, string propertyName)
{
return !Equals(OriginalValue(dbEntry, propertyName), CurrentValue(dbEntry, propertyName));
}
private static string OriginalValue(DbEntityEntry dbEntry, string propertyName)
{
string originalValue = null;
if (dbEntry.State == EntityState.Modified)
{
originalValue = dbEntry.OriginalValues.GetValue<object>(propertyName) == null
? null
: dbEntry.OriginalValues.GetValue<object>(propertyName).ToString();
}
return originalValue;
}
private static string CurrentValue(DbEntityEntry dbEntry, string propertyName)
{
string newValue;
try
{
newValue = dbEntry.CurrentValues.GetValue<object>(propertyName) == null
? null
: dbEntry.CurrentValues.GetValue<object>(propertyName).ToString();
}
catch (InvalidOperationException) // It will be invalid operation when its in deleted state. in that case, new value should be null
{
newValue = null;
}
return newValue;
}
}
Then I call it like this
// POST: Admin/Events/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(Event #event)
{
if (!ModelState.IsValid) { return View(#event); }
await _db.AddOrUpdate(#event);
await _db.SaveChangesAsync();
return RedirectToAction("Index");
}