0

我創建使用代碼第一個架構的實體,但運行應用程序其發電異常,當實體框架 - 無法確定類型之間關聯的主體結束?

Unable to determine the principal end of an association between the types 'WebApplication1.Models.DateOfProject' and 'WebApplication1.Models.Projects'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

我的方案是實施項目和DateOfProjects,使得1個項目有1 dateOfProject之間的關係1.1。

我的代碼是

public class Projects 
    { 
     [Key()] 
     [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)] 
     public int ProjectId { get; set; } 
     public string ProjectTitle { get; set; } 

     public string ProjectDescriptions { get; set; } 

     public DateOfProject DateOfProject { get; set; } 

     public virtual ICollection<ApplicationUser> ApplicationUser { get; set; } 

     public virtual ICollection<TaskSheetManagement> TaskSheetManagement { get; set; } 
    } 

    public class DateOfProject 
    { 
     public int DateOfProjectId { get; set; } 

     [ForeignKey("ProjectId")] 
     public Projects Projects { get; set; } 

     public DateTime DateOfProjectCreation { get; set; } 

     public Nullable<DateTime> ExpectedCompletionDate { get; set; } 

     public Nullable<DateTime> ProjectCompletionDate { get; set; } 


    } 

和DbContextClass inOnModelCreating函數內部

modelBuilder.Entity<Projects>().HasKey(pk => pk.ProjectId).ToTable("Projects"); 
modelBuilder.Entity<DateOfProject>().HasKey(pk => pk.DateOfProjectId).ToTable("DateOfProject"); 
modelBuilder.Entity<Projects>().HasRequired(p => p.DateOfProject).WithRequiredPrincipal(c => c.Projects); 

我不能只是解決這個問題。

+0

可能重複[無法確定關聯的原則結束](http://stackoverflow.com/questions/20035021/unable-to-determine-the-principle-end-of-an-association) – Colin

回答

0

如果你想要1:1的關係,你必須刪除[ForeignKey(「ProjectId」)]屬性。對於1:1關係,使用主鍵。如果你想要一個單獨的外鍵列,它是1:*關係。

相關問題