所以我有这些模型:
ParentModel.cs
public class ParentModel {
...properties here
//relationship to Child
[ForeignKey("ChildModelID")]
public ChildModel ChildModel { get; set; }
}
ChildModel.cs
public class ChildModel{
...properties here
//relationship to parent
[ForeignKey("ParentModel")]
public int? ParentModelID { get; set; }
public ParentModel ParentModel { get; set; }
}
我正在使用Web API Code-first。我是新来的。我在创建数据库时收到以下错误。但是,如果我删除ParentModel中的导航属性(即public ChildModel ChildModel { get; set; }
),一切正常,但它不能满足我的需要。当我得到ParentModel时,我想急切加载(或懒加载不确定哪个术语是正确的)ChildModel。这里的关系是零或一对一。这意味着ChildModel可以拥有一个在ParentModel中没有引用的记录。
Multiplicity is not valid in Role 'ChildModel_ParentModel_Source' in relationship
'ChildModel_ParentModel'. Because the Dependent Role properties are not the key
properties, the upper bound of the multiplicity of the Dependent Role must
be '*'.
提前谢谢!
答案 0 :(得分:2)
ChildModel和ParentModel是One-to-Zero / One
更新:
所以试试这段代码
public class ChildModel
{
public int Id { get; set; }
public ParentModel ParentModel { get; set; }
}
public class ParentModel
{
//[ForeignKey("ChildModel")]
//[Key]
public int ChildModelId { get; set; }
public ChildModel ChildModel { get; set; }
}
public class Context : DbContext
{
public DbSet<ChildModel> ChildModels { get; set; }
public DbSet<ParentModel> ParentModels { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ParentModel>().HasKey(s => s.ChildModelId);
modelBuilder.Entity<ParentModel>().HasRequired(s => s.ChildModel).WithOptional(s => s.ParentModel);
}
}
答案 1 :(得分:0)
我认为你混淆了ForeignKey
属性。不应该在ParentModel
上并参考ParentModelID
?
public class ChildModel
{
...properties here
//relationship to parent
public int? ParentModelID { get; set; }
[ForeignKey("ParentModelID")]
public ParentModel ParentModel { get; set; }
}