Entity Framework will only set related entity property to “null” if I first get the property

前端 未结 6 981
难免孤独
难免孤独 2021-01-14 00:50

Edit This seems to occur for any Entity property that references another entity in one direction. In other words, for the below example, the fact

6条回答
  •  臣服心动
    2021-01-14 01:22

    I am not happy with the official workaround:

        context.Entry(foo).Reference(f => f.Bar).CurrentValue = null;
    

    because it involves too much contextual knowledge by the user of the POCO object. My fix is to trigger a load of the lazy property when setting the value to null so that we do not get a false positive comparison from EF:

        public virtual User CheckoutUser
        {
            get { return checkoutUser; }
            set
            {
                if (value != null || !LazyPropertyIsNull(CheckoutUser))
                {
                    checkoutUser = value;
                }
            }
        }
    

    and in my base DbEntity class:

        protected bool LazyPropertyIsNull(T currentValue) where T : DbEntity
        {
            return (currentValue == null);
        }
    

    Passing the property to the LazyPropertyIsNull function triggers the lazy load and the correct comparison occurs.

    Please vote for this issue on the EF issues log:

提交回复
热议问题