2013-02-15 48 views
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.

有人可以對此發光嗎?

+0

是您最後一次編輯答案了嗎?也許你可以將它轉換爲答案並將其標記爲已接受。 – 2013-02-16 10:15:39

回答

0

我加入這個流利的API代碼:

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

MapKey是可選的,但我希望它可以只用註釋已經完成。

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; } 
}