开发者

Why is entity still validated when it is gone?

开发者 https://www.devze.com 2023-03-10 15:45 出处:网络
开发者_开发百科Add a new entity to a TrackableCollection (context.Entities.Add(entity)) (EntityState = New)
    开发者_开发百科
  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; }
    }


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()


try

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

then call

context.SaveChanges()

;)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号