In a new project we are using Entity Framework Core instead of EntityFramework 6.2.0. Works good but it causes a problem when updating a parents children while also inserting new children.
Example:
Current model:
public class Profile
{
public Profile()
{
Interests = new List<Interest>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public ICollection<Interest> Interests { get; set; }
}
public class Interest
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
}
Code to add or update children in Entity Framework, worked fine in EntityFramework 6.2.0
//Interests
//Delete children
foreach (var existingChild in dbProfile.Interests.ToList())
{
if (!profile.Interests.Any(c => c.Name == existingChild.Name))
db.Interests.Remove(existingChild);
}
//Update and Insert children
foreach (var childModel in profile.Interests)
{
var existingChild = dbProfile.Interests
.Where(c => c.Name == childModel.Name)
.SingleOrDefault();
if (existingChild != null)
{
// Update child
childModel.Id = existingChild.Id;
db.Entry(existingChild).CurrentValues.SetValues(childModel);
}
else
{
// Insert child
var newChild = new Interest
{
Name = childModel.Name,
};
dbProfile.Interests.Add(newChild);
}
}
Code is based on this answer:
https://stackoverflow.com/a/27177623/3850405
When using Microsoft.EntityFrameworkCore 2.2.6
this happens:
A new Interest is added with Id 0
as expected.
However if an update occurs and the following code is ran:
db.Entry(existingChild).CurrentValues.SetValues(childModel);
Every new object with Id 0
has their Id
set to -2147482197
. This happens even though nothing is set for the parent object, only a single child object. Why does this happen? Has something replaced the above method in EF Core?
I can solve this by removing db.Entry(existingChild).CurrentValues.SetValues(childModel);
and replace it with childModel.Name = existingChild.Name;
. But if the object had 20 or more properties I would not like to manually map them one by one.