Updating a list of foreign keys in EF4, using MVC 2 Repository Viewmodel Pattern - asp.net-mvc-2

Okay, I'm really struggling with how to update a list of foreign keys in MVC2/EF4.
I have a one to many relationship between a Template object which can have many or no TemplateScenario objects.
Essentially, I have an edit method in a controller that is trying to do this:
// POST: /Modes/Edit/1
[HttpPost]
public ActionResult Edit(int id, FormCollection formValues)
{
Template template = _templateRepository.GetTemplate(id);
TemplateCreateViewModel viewModel = new TemplateCreateViewModel();
viewModel.Template = template;
viewModel.TemplateScenarioList = template.TemplateScenarios.ToList();
//Update the model
UpdateModel(viewModel);
UpdateModel(viewModel.Template.TemplateScenarios, "TemplateScenarioList", new[] { "ScenarioID", "TemplateID" });
_templateRepository.Save();
return RedirectToAction("Edit", new { id = template.TemplateID });
}
This code successfully updates the 'template' object. It also adds the 'templatescenario' child objects BUT only if it is the first time I have added 'templatescenarios' to this particular template. If any templatescenario objects already exist for a given template, and I try to update them based on the new list, I get this error:
"The operation failed: The relationship could not be changed because one or more
of the foreign-key properties is non-nullable. When a change is made to a
relationship, the related foreign-key property is set to a null value. If the
foreign-key does not support null values, a new relationship must be defined,
the foreign-key property must be assigned another non-null value, or the
unrelated object must be deleted."
The _templateRepository.Save(); is just calling the entities.SaveChanges() EF4 method.
I can solve this in a dirty way by passing down a list of templatescenario ids to my repository class in a custom 'update' method that looks like this:
public void Update(Template template, IList<int> templateScenarios)
{
//Delete Old Entries
foreach (TemplateScenario ts in entities.TemplateScenarios)
{
if (ts.TemplateID == template.TemplateID)
{
if (templateScenarios == null)
entities.TemplateScenarios.DeleteObject(ts);
else if (!templateScenarios.Where(tsl => tsl == ts.ScenarioID).Any())
entities.TemplateScenarios.DeleteObject(ts);
}
}
//Don't need to add anything if they are null.
if (templateScenarios == null)
return;
//Add New Entries
foreach (int ts in templateScenarios)
{
if (!entities.TemplateScenarios.Where(tsc => tsc.ScenarioID == ts && tsc.TemplateID == template.TemplateID).Any())
{
TemplateScenario tempScenToAdd = new TemplateScenario();
tempScenToAdd.ScenarioID = ts;
tempScenToAdd.TemplateID = template.TemplateID;
entities.TemplateScenarios.AddObject(tempScenToAdd);
}
}
}
But that just feels dirty and I think I'm so close with the first, more automatic method. I've scoured the internet and found some similar posts on stackoverflow but am finding it difficult to reach that 'aha' moment.
Thanks,
Tom.

Incidently, I sorted out my problem.
The problem was my joining table was incorrectly using it's own primary key instead of using a composite key based on two foreign keys. This is obviously wrong /bad practice and EF4 and UpdateModel() don't play nice.
I had inherited the DB design from an ex-collegue and thus had taken the db design as correct without thinking too much about it. Very stupid of me, I know.

Related

Update object using only DbSet

I'm trying to apply the unit of work pattern as described in this blog, but have bumped into the following problem: If I inject the associated DbSet into the repo only, e.g.
public ArticleRepository(DbSet<Article> articles)
{
this.articles = articles;
}
then how do I update records or set their status to modified?
Before I used
public void Update(Article article)
{
this.context.Entry(article).State = EntityState.Modified;
}
but with the new approach I don't have access to DbContext anymore. Neither DbSet.Add nor DbSet.Attach will work here, so how can I update the object in the context?
System.Data.Entity.Migrations.IDbSetExtensions contains the IDbSet extension AddOrUpdate<TEntity>. This will update the entity.
Some people like the advantage of not knowing whether they are adding a new entity or changing an existing one.
However, if you really want an error if you are updating an item that is not added yet, take a look at the Source Code of IDbSetExtensions.AddOrUpdate
Here you can see that the function first checks if the item exists and depending on the result adds or updates it as follows:
var existing = set.SingleOrDefault
(Expression.Lambda<Func <TEntity, bool>> (matchExpression, new[]
{parameter}));
if (existing != null)
{ // entity exists: update it
foreach (var keyProperty in keyProperties)
{
keyProperty.Single().SetValue
(entity, keyProperty.Single().GetValue (existing, null), null);
}
internalSet.InternalContext.Owner.Entry(existing)
.CurrentValues.SetValues (entity);
}
else
{ // not existing entity: Add it
internalSet.Add(entity);
}
If you don't want the AddOrUpdate, but really only an update, consider Creating your own Extension method for IDbSet. See Extension Methods (C# Programming Guide)

In Entity Framework, take a newly created object and use it to update an existing record

Here's what I'd like to do:
var myCustomer = new Customer();
myCustomer.Name = "Bob";
myCustomer.HasAJob = true;
myCustomer.LikesPonies = false;
Then I'd like to pass it into an update method:
public UpdateCustomer(Customer cust)
{
using(var context = dbcontext())
{
var dbCust = context.Customers.FirstOrDefault(c => c.Name == cust.Name);
if(dbCust != null)
{
// Apply values from cust here so I don't have to do this:
dbCust.HasAJob = cust.HasAJob;
dbCust.LikesPonies = cust.LikesPonies
}
context.SaveChanges();
}
}
The reason for this is I'm working in multiple different parts of my application, and/or across DLLs. Is this possible?
EDIT: Found this question to be immensely useful:
Update Row if it Exists Else Insert Logic with Entity Framework
If you are sure that the entity is in the database and you have key you would just Attach the object you have to the context. Note that attached entities are by default in Unchanged state as the assumption is that all the values of properties are the same as in the database. If this is not the case (i.e. values are different) you need to change the state of the entity to modified. Take a look at this blog post: http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx it describes several sceanrios including the one you are asking about.

Add an Object to Entity Framework using a navigational property

Hi I use C# and EF 4.
I have two Entities CmsContent and CmsJob.
CmsJob has a navigational property to CmsContent.
I need add a CmsContent Object to CmsJob using the navigational property.
My code run with no error but I cannot persist the new entry om DataBase.
Could you tell me what I'm doing wrong?
Please provide me an example of code. Thanks for your support!
using (CmsConnectionStringEntityDataModel context = new CmsConnectionStringEntityDataModel())
{
CmsContent myContent = context.CmsContents.FirstOrDefault(x => x.ContentId == contentId);
CmsJob myJob = context.CmsJobs.FirstOrDefault(x => x.JobId == jobId);
myJob.CmsContents.Add(myContent);
}
Based on comments under #Hasan's answer you have incorrectly defined database. Your Job and Content are in many-to-many relation so you have junction table called CmsJobsContents but this table is missing primary key. Because of that it is read-only for EF and you cannot create new relations in your application. You must go to your database and mark both FKs in the CmsJobsContents as primary keys. After that update your model from database and you should be able to save changes.
That's because you haven't saved changes. Try this:
using (CmsConnectionStringEntityDataModel context = new CmsConnectionStringEntityDataModel())
{
CmsContent myContent = context.CmsContents.FirstOrDefault(x => x.ContentId == contentId);
CmsJob myJob = context.CmsJobs.FirstOrDefault(x => x.JobId == jobId);
myJob.CmsContents.Add(myContent);
context.SaveChanges();
}

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I am getting this error when I GetById() on an entity and then set the collection of child entities to my new list which comes from the MVC view.
The operation failed: The
relationship could not be changed
because one or more of the foreign-key
properties is non-nullable. When a
change is made to a relationship, the
related foreign-key property is set to
a null value. If the foreign-key does
not support null values, a new
relationship must be defined, the
foreign-key property must be assigned
another non-null value, or the
unrelated object must be deleted.
I don't quite understand this line:
The relationship could not be changed
because one or more of the foreign-key
properties is non-nullable.
Why would I change the relationship between 2 entities? It should remain the same throughout the lifetime of the whole application.
The code the exception occurs on is simple assigning modified child classes in a collection to the existing parent class. This would hopefully cater for removal of child classes, addition of new ones and modifications. I would have thought Entity Framework handles this.
The lines of code can be distilled to:
var thisParent = _repo.GetById(1);
thisParent.ChildItems = modifiedParent.ChildItems();
_repo.Save();
You should delete old child items thisParent.ChildItems one by one manually. Entity Framework doesn't do that for you. It finally cannot decide what you want to do with the old child items - if you want to throw them away or if you want to keep and assign them to other parent entities. You must tell Entity Framework your decision. But one of these two decisions you HAVE to make since the child entities cannot live alone without a reference to any parent in the database (due to the foreign key constraint). That's basically what the exception says.
Edit
What I would do if child items could be added, updated and deleted:
public void UpdateEntity(ParentItem parent)
{
// Load original parent including the child item collection
var originalParent = _dbContext.ParentItems
.Where(p => p.ID == parent.ID)
.Include(p => p.ChildItems)
.SingleOrDefault();
// We assume that the parent is still in the DB and don't check for null
// Update scalar properties of parent,
// can be omitted if we don't expect changes of the scalar properties
var parentEntry = _dbContext.Entry(originalParent);
parentEntry.CurrentValues.SetValues(parent);
foreach (var childItem in parent.ChildItems)
{
var originalChildItem = originalParent.ChildItems
.Where(c => c.ID == childItem.ID && c.ID != 0)
.SingleOrDefault();
// Is original child item with same ID in DB?
if (originalChildItem != null)
{
// Yes -> Update scalar properties of child item
var childEntry = _dbContext.Entry(originalChildItem);
childEntry.CurrentValues.SetValues(childItem);
}
else
{
// No -> It's a new child item -> Insert
childItem.ID = 0;
originalParent.ChildItems.Add(childItem);
}
}
// Don't consider the child items we have just added above.
// (We need to make a copy of the list by using .ToList() because
// _dbContext.ChildItems.Remove in this loop does not only delete
// from the context but also from the child collection. Without making
// the copy we would modify the collection we are just interating
// through - which is forbidden and would lead to an exception.)
foreach (var originalChildItem in
originalParent.ChildItems.Where(c => c.ID != 0).ToList())
{
// Are there child items in the DB which are NOT in the
// new child item collection anymore?
if (!parent.ChildItems.Any(c => c.ID == originalChildItem.ID))
// Yes -> It's a deleted child item -> Delete
_dbContext.ChildItems.Remove(originalChildItem);
}
_dbContext.SaveChanges();
}
Note: This is not tested. It's assuming that the child item collection is of type ICollection. (I usually have IList and then the code looks a bit different.) I've also stripped away all repository abstractions to keep it simple.
I don't know if that is a good solution, but I believe that some kind of hard work along these lines must be done to take care of all kinds of changes in the navigation collection. I would also be happy to see an easier way of doing it.
The reason you're facing this is due to the difference between composition and aggregation.
In composition, the child object is created when the parent is created and is destroyed when its parent is destroyed. So its lifetime is controlled by its parent. e.g. A blog post and its comments. If a post is deleted, its comments should be deleted. It doesn't make sense to have comments for a post that doesn't exist. Same for orders and order items.
In aggregation, the child object can exist irrespective of its parent. If the parent is destroyed, the child object can still exist, as it may be added to a different parent later. e.g.: the relationship between a playlist and the songs in that playlist. If the playlist is deleted, the songs shouldn't be deleted. They may be added to a different playlist.
The way Entity Framework differentiates aggregation and composition relationships is as follows:
For composition: it expects the child object to a have a composite primary key (ParentID, ChildID). This is by design as the IDs of the children should be within the scope of their parents.
For aggregation: it expects the foreign key property in the child object to be nullable.
So, the reason you're having this issue is because of how you've set your primary key in your child table. It should be composite, but it's not. So, Entity Framework sees this association as aggregation, which means, when you remove or clear the child objects, it's not going to delete the child records. It'll simply remove the association and sets the corresponding foreign key column to NULL (so those child records can later be associated with a different parent). Since your column does not allow NULL, you get the exception you mentioned.
Solutions:
1- If you have a strong reason for not wanting to use a composite key, you need to delete the child objects explicitly. And this can be done simpler than the solutions suggested earlier:
context.Children.RemoveRange(parent.Children);
2- Otherwise, by setting the proper primary key on your child table, your code will look more meaningful:
parent.Children.Clear();
This is a very big problem. What actually happens in your code is this:
You load Parent from the database and get an attached entity
You replace its child collection with new collection of detached children
You save changes but during this operation all children are considered as added becasue EF didn't know about them till this time. So EF tries to set null to foreign key of old children and insert all new children => duplicate rows.
Now the solution really depends on what you want to do and how would you like to do it?
If you are using ASP.NET MVC you can try to use UpdateModel or TryUpdateModel.
If you want just update existing children manually, you can simply do something like:
foreach (var child in modifiedParent.ChildItems)
{
context.Childs.Attach(child);
context.Entry(child).State = EntityState.Modified;
}
context.SaveChanges();
Attaching is actually not needed (setting the state to Modified will also attach the entity) but I like it because it makes the process more obvious.
If you want to modify existing, delete existing and insert new childs you must do something like:
var parent = context.Parents.GetById(1); // Make sure that childs are loaded as well
foreach(var child in modifiedParent.ChildItems)
{
var attachedChild = FindChild(parent, child.Id);
if (attachedChild != null)
{
// Existing child - apply new values
context.Entry(attachedChild).CurrentValues.SetValues(child);
}
else
{
// New child
// Don't insert original object. It will attach whole detached graph
parent.ChildItems.Add(child.Clone());
}
}
// Now you must delete all entities present in parent.ChildItems but missing
// in modifiedParent.ChildItems
// ToList should make copy of the collection because we can't modify collection
// iterated by foreach
foreach(var child in parent.ChildItems.ToList())
{
var detachedChild = FindChild(modifiedParent, child.Id);
if (detachedChild == null)
{
parent.ChildItems.Remove(child);
context.Childs.Remove(child);
}
}
context.SaveChanges();
I found this answer much more helpful for the same error.
It seems that EF does not like it when you Remove, it prefers Delete.
You can delete a collection of records attached to a record like this.
order.OrderDetails.ToList().ForEach(s => db.Entry(s).State = EntityState.Deleted);
In the example, all of the Detail records attached to an Order have their State set to Delete. (In preparation to Add back updated Details, as part of an Order update)
I've no idea why the other two answers are so popular!
I believe you were right in assuming the ORM framework should handle it - after all, that is what it promises to deliver. Otherwise your domain model gets corrupted by persistence concerns. NHibernate manages this happily if you setup the cascade settings correctly. In Entity Framework it is also possible, they just expect you to follow better standards when setting up your database model, especially when they have to infer what cascading should be done:
You have to define the parent - child relationship correctly by using an "identifying relationship".
If you do this, Entity Framework knows the child object is identified by the parent, and therefore it must be a "cascade-delete-orphans" situation.
Other than the above, you might need to (from NHibernate experience)
thisParent.ChildItems.Clear();
thisParent.ChildItems.AddRange(modifiedParent.ChildItems);
instead of replacing the list entirely.
UPDATE
#Slauma's comment reminded me that detached entities are another part of the overall problem. To solve that, you can take the approach of using a custom model binder that constructs your models by attempting to load it from the context. This blog post shows an example of what I mean.
If you are using AutoMapper with Entity Framework on the same class, you might hit this problem. For instance if your class is
class A
{
public ClassB ClassB { get; set; }
public int ClassBId { get; set; }
}
AutoMapper.Map<A, A>(input, destination);
This will try to copy both properties. In this case, ClassBId is non Nullable. Since AutoMapper will copy destination.ClassB = input.ClassB; this will cause a problem.
Set your AutoMapper to Ignore ClassB property.
cfg.CreateMap<A, A>()
.ForMember(m => m.ClassB, opt => opt.Ignore()); // We use the ClassBId
I had same problem, but I knew it had worked OK in other cases, so I reduced the problem to this:
parent.OtherRelatedItems.Clear(); //this worked OK on SaveChanges() - items were being deleted from DB
parent.ProblematicItems.Clear(); // this was causing the mentioned exception on SaveChanges()
OtherRelatedItems had a composite Primary Key (parentId + some local column) and worked OK
ProblematicItems had their own single-column Primary Key, and the parentId was only a FK. This was causing the exception after Clear().
All I had to do was to make the ParentId a part of composite PK to indicate that the children can't exist without a parent. I used DB-first model, added the PK and marked the parentId column as EntityKey (so, I had to update it both in DB and EF - not sure if EF alone would be enough).
Once you think about it, it's a very elegant distinction that EF uses to decide if children "make sense" without a parent (in this case Clear() won't delete them and throw exception unless you set the ParentId to something else/special), or - like in the original question - we expect the items to be deleted once they are removed from the parent.
I just had the same error.
I have two tables with a parent child relationship, but I configured a "on delete cascade" on the foreign key column in the table definition of the child table.
So when I manually delete the parent row (via SQL) in the database it will automatically delete the child rows.
However this did not work in EF, the error described in this thread showed up.
The reason for this was, that in my entity data model (edmx file) the properties of the association between the parent and the child table were not correct.
The End1 OnDelete option was configured to be none ("End1" in my model is the end which has a multiplicity of 1).
I manually changed the End1 OnDelete option to Cascade and than it worked.
I do not know why EF is not able to pick this up, when I update the model from the database (I have a database first model).
For completeness, this is how my code to delete looks like:
public void Delete(int id)
{
MyType myObject = _context.MyTypes.Find(id);
_context.MyTypes.Remove(myObject);
_context.SaveChanges();
}
If I hadn´t a cascade delete defined, I would have to delete the child rows manually before deleting the parent row.
This happens because the Child Entity is marked as Modified instead of Deleted.
And the modification that EF does to the Child Entity when parent.Remove(child) is executed, is simply setting the reference to its parent to null.
You can check the child's EntityState by typing the following code into Visual Studio's Immediate Window when the exception occurs, after executing SaveChanges():
_context.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified).ElementAt(X).Entity
where X should be replaced by the deleted Entity.
If you don't have access to the ObjectContext to execute _context.ChildEntity.Remove(child), you can solve this issue by making the foreign key a part of the primary key on the child table.
Parent
________________
| PK IdParent |
| Name |
|________________|
Child
________________
| PK IdChild |
| PK,FK IdParent |
| Name |
|________________|
This way, if you execute parent.Remove(child), EF will correctly mark the Entity as Deleted.
This type of solution did the trick for me:
Parent original = db.Parent.SingleOrDefault<Parent>(t => t.ID == updated.ID);
db.Childs.RemoveRange(original.Childs);
updated.Childs.ToList().ForEach(c => original.Childs.Add(c));
db.Entry<Parent>(original).CurrentValues.SetValues(updated);
Its important to say that this deletes all the records and insert them again.
But for my case (less then 10) it´s ok.
I hope it helps.
I ran into this problem today and wanted to share my solution. In my case, the solution was to delete the Child items before getting the Parent from the database.
Previously I was doing it like in the code below. I will then get the same error listed in this question.
var Parent = GetParent(parentId);
var children = Parent.Children;
foreach (var c in children )
{
Context.Children.Remove(c);
}
Context.SaveChanges();
What worked for me, is to get the children items first, using the parentId (foreign key) and then delete those items. Then I can get the Parent from the database and at that point, it should not have any children items anymore and I can add new children items.
var children = GetChildren(parentId);
foreach (var c in children )
{
Context.Children.Remove(c);
}
Context.SaveChanges();
var Parent = GetParent(parentId);
Parent.Children = //assign new entities/items here
You must manually clear the ChildItems collection and append new items into it:
thisParent.ChildItems.Clear();
thisParent.ChildItems.AddRange(modifiedParent.ChildItems);
After that you can call DeleteOrphans extension method which will handle with orphaned entities (it must be called between DetectChanges and SaveChanges methods).
public static class DbContextExtensions
{
private static readonly ConcurrentDictionary< EntityType, ReadOnlyDictionary< string, NavigationProperty>> s_navPropMappings = new ConcurrentDictionary< EntityType, ReadOnlyDictionary< string, NavigationProperty>>();
public static void DeleteOrphans( this DbContext source )
{
var context = ((IObjectContextAdapter)source).ObjectContext;
foreach (var entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
{
var entityType = entry.EntitySet.ElementType as EntityType;
if (entityType == null)
continue;
var navPropMap = s_navPropMappings.GetOrAdd(entityType, CreateNavigationPropertyMap);
var props = entry.GetModifiedProperties().ToArray();
foreach (var prop in props)
{
NavigationProperty navProp;
if (!navPropMap.TryGetValue(prop, out navProp))
continue;
var related = entry.RelationshipManager.GetRelatedEnd(navProp.RelationshipType.FullName, navProp.ToEndMember.Name);
var enumerator = related.GetEnumerator();
if (enumerator.MoveNext() && enumerator.Current != null)
continue;
entry.Delete();
break;
}
}
}
private static ReadOnlyDictionary<string, NavigationProperty> CreateNavigationPropertyMap( EntityType type )
{
var result = type.NavigationProperties
.Where(v => v.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
.Where(v => v.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One || (v.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne && v.FromEndMember.GetEntityType() == v.ToEndMember.GetEntityType()))
.Select(v => new { NavigationProperty = v, DependentProperties = v.GetDependentProperties().Take(2).ToArray() })
.Where(v => v.DependentProperties.Length == 1)
.ToDictionary(v => v.DependentProperties[0].Name, v => v.NavigationProperty);
return new ReadOnlyDictionary<string, NavigationProperty>(result);
}
}
I've tried these solutions and many others, but none of them quite worked out. Since this is the first answer on google, I'll add my solution here.
The method that worked well for me was to take relationships out of the picture during commits, so there was nothing for EF to screw up. I did this by re-finding the parent object in the DBContext, and deleting that. Since the re-found object's navigation properties are all null, the childrens' relationships are ignored during the commit.
var toDelete = db.Parents.Find(parentObject.ID);
db.Parents.Remove(toDelete);
db.SaveChanges();
Note that this assumes the foreign keys are setup with ON DELETE CASCADE, so when the parent row is removed, the children will be cleaned up by the database.
I used Mosh's solution, but it was not obvious to me how to implement the composition key correctly in code first.
So here is the solution:
public class Holiday
{
[Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int HolidayId { get; set; }
[Key, Column(Order = 1), ForeignKey("Location")]
public LocationEnum LocationId { get; set; }
public virtual Location Location { get; set; }
public DateTime Date { get; set; }
public string Name { get; set; }
}
If you are using Auto mapper and facing the the issue following is the good solution, it work for me
https://www.codeproject.com/Articles/576393/Solutionplusto-aplus-Theplusoperationplusfailed
Since the problem is that we're mapping null navigation properties, and we actually don't need them to be updated on the Entity since they didn't changed on the Contract, we need to ignore them on the mapping definition:
ForMember(dest => dest.RefundType, opt => opt.Ignore())
So my code ended up like this:
Mapper.CreateMap<MyDataContract, MyEntity>
ForMember(dest => dest.NavigationProperty1, opt => opt.Ignore())
ForMember(dest => dest.NavigationProperty2, opt => opt.Ignore())
.IgnoreAllNonExisting();
This issue arise because we try to delete the parent table still child table data is present.
We solve the problem with help of cascade delete.
In model Create method in dbcontext class.
modelBuilder.Entity<Job>()
.HasMany<JobSportsMapping>(C => C.JobSportsMappings)
.WithRequired(C => C.Job)
.HasForeignKey(C => C.JobId).WillCascadeOnDelete(true);
modelBuilder.Entity<Sport>()
.HasMany<JobSportsMapping>(C => C.JobSportsMappings)
.WithRequired(C => C.Sport)
.HasForeignKey(C => C.SportId).WillCascadeOnDelete(true);
After that,In our API Call
var JobList = Context.Job
.Include(x => x.JobSportsMappings) .ToList();
Context.Job.RemoveRange(JobList);
Context.SaveChanges();
Cascade delete option delete the parent as well parent related child table with this simple code. Make it try in this simple way.
Remove Range which used for delete the list of records in the database
Thanks
I also solved my problem with Mosh's answer and I thought PeterB's answer was a bit of since it used an enum as foreign key. Remember that you will need to add a new migration after adding this code.
I can also recommend this blog post for other solutions:
http://www.kianryan.co.uk/2013/03/orphaned-child/
Code:
public class Child
{
[Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Heading { get; set; }
//Add other properties here.
[Key, Column(Order = 1)]
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Using the solution of Slauma, I created some generic functions to help update child objects and collections of child objects.
All my persistent objects implement this interface
/// <summary>
/// Base interface for all persisted entries
/// </summary>
public interface IBase
{
/// <summary>
/// The Id
/// </summary>
int Id { get; set; }
}
With this I implemented these two functions in my Repository
/// <summary>
/// Check if orgEntry is set update it's values, otherwise add it
/// </summary>
/// <param name="set">The collection</param>
/// <param name="entry">The entry</param>
/// <param name="orgEntry">The original entry found in the database (can be <code>null</code> is this is a new entry)</param>
/// <returns>The added or updated entry</returns>
public T AddOrUpdateEntry<T>(DbSet<T> set, T entry, T orgEntry) where T : class, IBase
{
if (entry.Id == 0 || orgEntry == null)
{
entry.Id = 0;
return set.Add(entry);
}
else
{
Context.Entry(orgEntry).CurrentValues.SetValues(entry);
return orgEntry;
}
}
/// <summary>
/// check if each entry of the new list was in the orginal list, if found, update it, if not found add it
/// all entries found in the orignal list that are not in the new list are removed
/// </summary>
/// <typeparam name="T">The type of entry</typeparam>
/// <param name="set">The database set</param>
/// <param name="newList">The new list</param>
/// <param name="orgList">The original list</param>
public void AddOrUpdateCollection<T>(DbSet<T> set, ICollection<T> newList, ICollection<T> orgList) where T : class, IBase
{
// attach or update all entries in the new list
foreach (T entry in newList)
{
// Find out if we had the entry already in the list
var orgEntry = orgList.SingleOrDefault(e => e.Id != 0 && e.Id == entry.Id);
AddOrUpdateEntry(set, entry, orgEntry);
}
// Remove all entries from the original list that are no longer in the new list
foreach (T orgEntry in orgList.Where(e => e.Id != 0).ToList())
{
if (!newList.Any(e => e.Id == orgEntry.Id))
{
set.Remove(orgEntry);
}
}
}
To use it i do the following:
var originalParent = _dbContext.ParentItems
.Where(p => p.Id == parent.Id)
.Include(p => p.ChildItems)
.Include(p => p.ChildItems2)
.SingleOrDefault();
// Add the parent (including collections) to the context or update it's values (except the collections)
originalParent = AddOrUpdateEntry(_dbContext.ParentItems, parent, originalParent);
// Update each collection
AddOrUpdateCollection(_dbContext.ChildItems, parent.ChildItems, orgiginalParent.ChildItems);
AddOrUpdateCollection(_dbContext.ChildItems2, parent.ChildItems2, orgiginalParent.ChildItems2);
Hope this helps
EXTRA: You could also make a seperate DbContextExtentions (or your own context inferface) class:
public static void DbContextExtentions {
/// <summary>
/// Check if orgEntry is set update it's values, otherwise add it
/// </summary>
/// <param name="_dbContext">The context object</param>
/// <param name="set">The collection</param>
/// <param name="entry">The entry</param>
/// <param name="orgEntry">The original entry found in the database (can be <code>null</code> is this is a new entry)</param>
/// <returns>The added or updated entry</returns>
public static T AddOrUpdateEntry<T>(this DbContext _dbContext, DbSet<T> set, T entry, T orgEntry) where T : class, IBase
{
if (entry.IsNew || orgEntry == null) // New or not found in context
{
entry.Id = 0;
return set.Add(entry);
}
else
{
_dbContext.Entry(orgEntry).CurrentValues.SetValues(entry);
return orgEntry;
}
}
/// <summary>
/// check if each entry of the new list was in the orginal list, if found, update it, if not found add it
/// all entries found in the orignal list that are not in the new list are removed
/// </summary>
/// <typeparam name="T">The type of entry</typeparam>
/// <param name="_dbContext">The context object</param>
/// <param name="set">The database set</param>
/// <param name="newList">The new list</param>
/// <param name="orgList">The original list</param>
public static void AddOrUpdateCollection<T>(this DbContext _dbContext, DbSet<T> set, ICollection<T> newList, ICollection<T> orgList) where T : class, IBase
{
// attach or update all entries in the new list
foreach (T entry in newList)
{
// Find out if we had the entry already in the list
var orgEntry = orgList.SingleOrDefault(e => e.Id != 0 && e.Id == entry.Id);
AddOrUpdateEntry(_dbContext, set, entry, orgEntry);
}
// Remove all entries from the original list that are no longer in the new list
foreach (T orgEntry in orgList.Where(e => e.Id != 0).ToList())
{
if (!newList.Any(e => e.Id == orgEntry.Id))
{
set.Remove(orgEntry);
}
}
}
}
and use it like:
var originalParent = _dbContext.ParentItems
.Where(p => p.Id == parent.Id)
.Include(p => p.ChildItems)
.Include(p => p.ChildItems2)
.SingleOrDefault();
// Add the parent (including collections) to the context or update it's values (except the collections)
originalParent = _dbContext.AddOrUpdateEntry(_dbContext.ParentItems, parent, originalParent);
// Update each collection
_dbContext.AddOrUpdateCollection(_dbContext.ChildItems, parent.ChildItems, orgiginalParent.ChildItems);
_dbContext.AddOrUpdateCollection(_dbContext.ChildItems2, parent.ChildItems2, orgiginalParent.ChildItems2);
I was face same problem when I am going to delete my record than some issue was occur , for this issue solution is that when you are going to delete your record than you missing some thing before deleting header/master record you must write to code for delete its detail before header/Master I hope you issue will be resolve.
I had the same issue when I was trying to modify the scalar property of the targeted entity and realized I have accidentally referenced the target entity's parent:
entity.GetDbContextFromEntity().Entry(entity).Reference(i => i.ParentEntity).Query().Where(p => p.ID == 1).Load();
Just an advice by making sure the target entity does not reference any parent.
I've met this problem before several hours and try everything, but in my case the solution was diferent from the listed above.
If you use already retrieved entity from the database and try to modify it's childrens the error will occure, but if you get fresh copy of the entity from the database there should not be any problems.
Do not use this:
public void CheckUsersCount(CompanyProduct companyProduct)
{
companyProduct.Name = "Test";
}
Use this:
public void CheckUsersCount(Guid companyProductId)
{
CompanyProduct companyProduct = CompanyProductManager.Get(companyProductId);
companyProduct.Name = "Test";
}

Convince entity context (EF1) to populate entity references

I have an entity with self reference (generated by Entity Designer):
public MyEntity: EntityObject
{
// only relevant stuff here
public int Id { get...; set...; }
public MyEntity Parent { get...; set...; }
public EntityCollection<MyEntity> Children { get...; set...; }
...
}
I've written a stored procedure that returns a subtree of nodes (not just immediate children) from the table and returns a list of MyEntity objects. I'm using a stored proc to avoid lazy loading of an arbitrary deep tree. This way I get relevant subtree nodes back from the DB in a single call.
List<MyEntity> nodes = context.GetSubtree(rootId).ToList();
All fine. But when I check nodes[0].Children, its Count equals to 0. But if I debug and check context.MyEntities.Results view, Children enumerations get populated. Checking my result reveals children under my node[0].
How can I programaticaly force my entity context to do in-memory magic and put correct references on Parent and Children properties?
UPDATE 1
I've tried calling
context.Refresh(ClientWins, nodes);
after my GetSubtree() call which does set relations properly, but fetches same nodes again from the DB. It's still just a workaround. But better than getting the whole set with context.MyEntities().ToList().
UPDATE 2
I've reliably solved this by using EF Extensions project. Check my answer below.
You need to assign one end of the relationship. First, divide the collection:
var root = nodes.Where(n => n.Id == rootId).First();
var children = nodes.Where(n => n.Id != rootId);
Now, fix up the relationship.
In your case, you'd do either:
foreach (var c in children)
{
c.Parent = root;
}
...or:
foreach (var c in children)
{
root.Children.Add(c);
}
It doesn't matter which.
Note that this marks the entities as modfied. You'll need to change that if you intend to call SaveChanges on the context and don't want this saved.
The REAL solution
Based on this article (read text under The problem), navigation properties are obviously not populated/updated when one uses stored procedures to return data.
But there's a nice manual solution to this. Use EF Extensions project and write your own entity Materilizer<EntityType> where you can correctly set navigation properties like this:
...
ParentReference = {
EntityKey = new EntityKey(
"EntityContextName.ParentEntitySetname",
new[] {
new EntityKeyMember(
"ParentEntityIdPropertyName",
reader.Field<int>("FKNameFromSP")
)
})
}
...
And that's it. Calling stored procedure will return correct data, and entity object instances will be correctly related to eachother. I advise you check EF Extensions' samples, where you will find lots of nice things.