我在通过 Code-First 将模型与实体框架映射时遇到问题,这是我模型的简短版本:
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 中创建了一个新行,而不是更新现有行;我尝试将导航属性添加到不同的实体级别,但它再次不起作用。有没有办法从项目实体映射这个 DemographicItem 集合?
更新:感谢 Gert Arnold 但它不起作用,在将新项目添加到 DemographicItems 后,数据库中的对应表填充了新行和新 ID。但是这个新条目有空项目。