Why is entity still validated when it is gone?
Asked Answered
V

2

12
  1. Add a new entity to a TrackableCollection (context.Entities.Add(entity)) (EntityState = New)
  2. Without saving, delete the added entity from TrackableCollection (context.Entities.Remove(entity)) (EntityState = Unmodified)
  3. Save. (context.SubmitChanges())

I still get validation errors from the data annotations associated with the entity, why?

    public class Entity
    {
       [Required]
       public string Name { get; set; }
    }
Voltaic answered 6/6, 2011 at 20:40 Comment(0)
L
1

It is tracking the collection of removed entities, even though it was not persisted to your store (it's in the ObjectsRemovedFromCollection property).

This link has more information about what is going on under the hood: MSDN

I'm not finding details about what explicitly triggers validation, but you can try calling AcceptChanges() or ObjectsAddedToCollectionProperties.Clear() and ObjectsRemovedFromCollectionProperties.Clear() before calling context.SubmitChanges()

Linkman answered 7/6, 2011 at 22:38 Comment(1)
Hmm those members don't seem to exist for me.Voltaic
M
0

try

context.Entry(entity).State = EntityState.Detached

then call

context.SaveChanges()

;)

Maurinemaurise answered 23/6, 2011 at 7:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.