0

当我有 2 个这样的模型时:

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.

有人可以对此有所了解吗?

4

2 回答 2

0

我添加了这个 Fluent API 代码:

        modelBuilder.Entity<PredictionGroup>()
            .HasOptional(m => m.ResultPrediction)
            .WithOptionalDependent()
            .Map(x => x.MapKey("PredictionResultGroupId"));

MapKey是可选的,但我希望它可以只用注释来完成。

于 2013-02-16T20:33:11.507 回答
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; }
}
于 2013-02-17T18:15:53.957 回答