“Entity Framwork Update Entidad matriz agregada nueva subcidad” Código de respuesta

Entity Framwork Update Entidad matriz agregada nueva subcidad

//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);
    }
}
Confused Cobra

Entity Framwork Update Entidad matriz agregada nueva subcidad

protected void UpdateChildCollection<Tparent, Tid , Tchild>(Tparent dbItem, Tparent newItem, Func<Tparent, IEnumerable<Tchild>> selector, Func<Tchild, Tid> idSelector) where Tchild : class
    {
        var dbItems = selector(dbItem).ToList();
        var newItems = selector(newItem).ToList();

        if (dbItems == null && newItems == null)
            return;

        var original = dbItems?.ToDictionary(idSelector) ?? new Dictionary<Tid, Tchild>();
        var updated = newItems?.ToDictionary(idSelector) ?? new Dictionary<Tid, Tchild>();

        var toRemove = original.Where(i => !updated.ContainsKey(i.Key)).ToArray();
        var removed = toRemove.Select(i => DbContext.Entry(i.Value).State = EntityState.Deleted).ToArray();

        var toUpdate = original.Where(i => updated.ContainsKey(i.Key)).ToList();
        toUpdate.ForEach(i => DbContext.Entry(i.Value).CurrentValues.SetValues(updated[i.Key]));

        var toAdd = updated.Where(i => !original.ContainsKey(i.Key)).ToList();
        toAdd.ForEach(i => DbContext.Set<Tchild>().Add(i.Value));
    }
Confused Cobra

Respuestas similares a “Entity Framwork Update Entidad matriz agregada nueva subcidad”

Preguntas similares a “Entity Framwork Update Entidad matriz agregada nueva subcidad”

Más respuestas relacionadas con “Entity Framwork Update Entidad matriz agregada nueva subcidad” en C#

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código