我使用代码优先模式创建实体,但在运行应用程序时生成异常
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.
我的方案是在Projects和DateOfProjects之间实现1.1关系,这样1个项目就有1个dateOfProject。
我的代码是
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 :(得分:0)
如果你想要一个1:1的关系,你必须删除[ForeignKey(&#34; ProjectId&#34;)]属性。对于1:1关系,使用主键。如果您想要一个单独的外键列,则它是1:*关系。