代码之家  ›  专栏  ›  技术社区  ›  Beau D'Amore

LINQ/Code first:如何从父对象中删除子对象的引用?

  •  1
  • Beau D'Amore  · 技术社区  · 10 年前

    我使用Repository模式以1:1的关系拥有“UserProfile”和“Executive”对象。UserProfile是系统的必需/一部分,而执行人员基于UserProfile。

    这是我的UserProfile:(相关部分)

    public int? ExecutiveId { get; set; }
    [ForeignKey("ExecutiveId")]
    public virtual Executive Executive { get; set; }
    

    这是我的主管:(相关部分)

    public int UserProfileId { get; set; }
    [ForeignKey("UserProfileId")]
    public virtual UserProfile UserProfile { get; set; }
    

    这是我的FluentApi:(因为高管是可选的,需要UserProfile)

    modelBuilder.Entity<Executive>()
                .HasRequired(x => x.UserProfile)
                .WithOptional(s => s.Executive)
                .WillCascadeOnDelete(false); <-- I've tried 'true' here as well
    

    现在,当我尝试删除它,并在SQL Mgr中查找时,我看到我删除的特定执行人员的UserProfile仍然是一个整数,而不是预期的NULL……下面是我要删除的代码:

     var executive = _executiveRepository.GetExecutiveById(id);
            // remove pic/content
            _contentRepository.DeleteContent(executive.ProfilePictureContent.ContentGuid);
            // remove mappings
            _executiveSectionMappingRepository.DeleteExecutiveSectionMappingRange(executive.ExecutiveSectionMappings);
            // remove executive
            _executiveRepository.DeleteExecutive(id);
            // remove reference from User also as EF isn't doing this the way it's setup now.
            var u = _userRepository
                .GetUserProfiles()
                .FirstOrDefault(x => x.ExecutiveId == executive.UserProfileId);
            if (u != null)
            {
                u.ExecutiveId = null;<-- these don't work !!
                u.Executive = null;  <-- not working
            }
            // save
            _contentRepository.Save();
            _executiveSectionMappingRepository.Save();
            _executiveRepository.Save();
            _userRepository.Save();
    

    我错过了什么? enter image description here

    1 回复  |  直到 10 年前
        1
  •  2
  •   John Grabanski AMissico    10 年前

    我没有先使用代码,但它看起来像是保存存储库,但没有设置要修改的实体。

    这意味着您正在更新内存中的userProfile对象,但不将repo设置为使用该对象。{除非我误解了“代码优先”},但您似乎需要按照以下内容进行操作:

    _userRepository.UpdateExistingUser(u);
    

    然后调用_userRepository.Save();