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

前端 未结 6 983
难免孤独
难免孤独 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:33

    If you want to avoid manipulating the EntityEntry, you can avoid the lazy load call to the database by including the FK property in your POCO (which you can make private if you don't want users to have access) and have the Nav property setter set that FK value to null if the setter value is null. Example:

    public class InaccessibleFKDependent
    {
        [Key]
        public int Id { get; set; }
        private int? PrincipalId { get; set; }
        private InaccessibleFKPrincipal _principal;
        public virtual InaccessibleFKPrincipal Principal
        {
            get => _principal;
            set
            {
                if( null == value )
                {
                    PrincipalId = null;
                }
    
                _principal = value;
            }
        }
    }
    
    public class InaccessibleFKDependentConfiguration : IEntityTypeConfiguration
    {
        public void Configure( EntityTypeBuilder builder )
        {
            builder.HasOne( d => d.Principal )
                .WithMany()
                .HasForeignKey( "PrincipalId" );
        }
    }
    

    Test:

        public static void TestInaccessibleFKSetToNull( DbContextOptions options )
        {
            using( var dbContext = DeleteAndRecreateDatabase( options ) )
            {
                var p = new InaccessibleFKPrincipal();
    
                dbContext.Add( p );
                dbContext.SaveChanges();
    
                var d = new InaccessibleFKDependent()
                {
                    Principal = p,
                };
    
                dbContext.Add( d );
                dbContext.SaveChanges();
            }
    
            using( var dbContext = new TestContext( options ) )
            {
                var d = dbContext.InaccessibleFKDependentEntities.Single();
                d.Principal = null;
                dbContext.SaveChanges();
            }
    
            using( var dbContext = new TestContext( options ) )
            {
                var d = dbContext.InaccessibleFKDependentEntities
                    .Include( dd => dd.Principal )
                    .Single();
    
                System.Console.WriteLine( $"{nameof( d )}.{nameof( d.Principal )} is NULL: {null == d.Principal}" );
            }
        }
    

提交回复
热议问题