[英]LINQ/Code first: how do I delete a child object's reference from the parent object?
I have 'UserProfile' and 'Executive' objects on a 1:1 relationship using Repository pattern. 我使用存储库模式以1:1关系具有“ UserProfile”和“ Executive”对象。 UserProfiles are required/part of the system, and executives are based on UserProfiles. UserProfile是必需的/是系统的一部分,主管人员基于UserProfile。
Here's my UserProfile:(pertinent part) 这是我的UserProfile :(相关部分)
public int? ExecutiveId { get; set; }
[ForeignKey("ExecutiveId")]
public virtual Executive Executive { get; set; }
Here's my Executive: (pertinent part) 这是我的行政人员:(相关部分)
public int UserProfileId { get; set; }
[ForeignKey("UserProfileId")]
public virtual UserProfile UserProfile { get; set; }
Here's my FluentApi:(since the executive is optional and requires a UserProfile) 这是我的FluentApi :(因为执行程序是可选的,并且需要UserProfile)
modelBuilder.Entity<Executive>()
.HasRequired(x => x.UserProfile)
.WithOptional(s => s.Executive)
.WillCascadeOnDelete(false); <-- I've tried 'true' here as well
Now when I try deleting it, and look in SQL Mgr, I see the UserProfile for a particular executive I've deleted is still an integer and not NULL as I expect... Here's my code to delete: 现在,当我尝试删除它并查看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();
I've not work with Code first, but it looks like your saving your Repositories, but not setting that entity to be modified. 我没有先使用Code,但是好像您在保存存储库,但未设置要修改的实体。
Meaning you're updating the userProfile's object in memory, but not setting your repo to use that object. 这意味着您正在更新内存中的userProfile对象,但未将存储库设置为使用该对象。 {unless i'm mistaken with Code First}, but it seems you need to do something along the lines of: {除非我误认为Code First},但似乎您需要采取以下措施:
_userRepository.UpdateExistingUser(u);
Then call _userRepository.Save(); 然后调用_userRepository.Save();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.