当我有两个这样的模型时:
public class PredictionGroup
{
[Key]
public Guid PredictionGroupId { get; set; }
public Guid? ResultPredictionId { get; set; }
[ForeignKey("ResultPredictionId")]
public Prediction ResultPrediction { get; set; }
public List<Prediction> Predictions { get; set; }
}
public class Prediction
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid PredictionId { get; set; }
[Required]
public Guid PredictionGroupId { get; set; }
[ForeignKey("PredictionGroupId")]
public PredictionGroup PredictionGroup { get; set; }
}
这将生成:
CreateTable(
"Website.PredictionGroups",
c => new
{
PredictionGroupId = c.Guid(nullable: false, identity: true),
ResultPredictionId = c.Guid(),
})
.PrimaryKey(t => t.PredictionGroupId)
.ForeignKey("Website.Predictions", t => t.ResultPredictionId)
.Index(t => t.ResultPredictionId);
CreateTable(
"Website.Predictions",
c => new
{
PredictionId = c.Guid(nullable: false, identity: true),
PredictionGroupId = c.Guid(nullable: false),
PredictionGroup_PredictionGroupId = c.Guid(),
})
.PrimaryKey(t => t.PredictionId)
.ForeignKey("Website.PredictionGroups", t => t.PredictionGroupId)
.ForeignKey("Website.PredictionGroups", t => t.PredictionGroup_PredictionGroupId)
.Index(t => t.PredictionGroupId)
.Index(t => t.PredictionGroup_PredictionGroupId);
当我尝试在我的数据库中输入此内容时,我收到错误:Unable to determine the principal end of the 'Site.Data.Prediction_PredictionGroup' relationship. Multiple added entities may have the same primary key.
有人可以对此发光吗?
答案 0 :(得分:0)
我添加了这个Fluent API代码:
modelBuilder.Entity<PredictionGroup>()
.HasOptional(m => m.ResultPrediction)
.WithOptionalDependent()
.Map(x => x.MapKey("PredictionResultGroupId"));
MapKey
是可选的,但我希望只使用注释即可完成。
答案 1 :(得分:0)
我不确定您的模型是否正确,这就是您需要添加Fluent API代码的原因。您不应该需要Fluent API代码。 [ForeignKey]定义在属性上进行,该属性是外键值,并指向它是键的对象。因此属性属性在ResultPredictionId上,并为属性ResultPrediction表示。目前它正好相反。
public class PredictionGroup
{
[Key]
public Guid PredictionGroupId { get; set; }
[ForeignKey("ResultPrediction")] //this is the key, point it to the object
public Guid? ResultPredictionId { get; set; }
public Prediction ResultPrediction { get; set; }
public List<Prediction> Predictions { get; set; }
}
public class Prediction
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid PredictionId { get; set; }
[Required]
[ForeignKey("PredictionGroup")]
public Guid PredictionGroupId { get; set; }
public PredictionGroup PredictionGroup { get; set; }
}