我無法對應的代碼先用實體框架模型的問題,這是我的模型的短版:在EF代碼更新收藏首先
public class Project
{
public int ProjectId { get; set; }
public string Name { get; set; }
public virtual ProjectPolicies Policies { get; set; }
public int ProjectPoliciesId { get; set; }
}
public class ProjectPolicies
{
public int ProjectPoliciesId { get; set; }
public DemographicInformation DemographicInformation { get; set; }
public int DemographicInformationId { get; set; }
}
public class DemographicInformation
{
public int DemographicInformationId { get; set; }
public virtual List<DemographicItem> Items { get; set; }
}
public class DemographicItem
{
public int DemographicItemId { get; set; }
public string Key { get; set; }
public DemographicValueType Type { get; set; }
public string Value { get; set; }
public DemographicInformation DemographicInformation { get; set; }
}
當我嘗試添加一個新的DemographicItem:
var project = this.myDbContext.Projects.Where(p => p.ProjectId.Equals(id)).First();
project.ProjectPolicies.DemographicInformation.DemographicItems.Add(item);
this.myRepository.Entry<Project>(project);
this.myDbContext.SaveChanges();
它不起作用,因爲它創建一個新的行到數據庫表DemographicInformations而不是更新現有的;我試圖將導航屬性添加到不同的實體級別,但它又不起作用。有沒有辦法從Project Entity映射這個DemographicItem集合?
更新:感謝Gert Arnold但它沒有工作,在向DemographicItems中添加一個新項目後,通訊員表中填入新行和新ID。但是這個新條目有空項目。
嗨,這只是現在,我碰巧看到你的更新。最好將這些評論添加到答案中,因爲答案者會收到通知。 –