【发布时间】:2014-08-14 01:33:18
【问题描述】:
我正在使用代码优先模式创建实体,但是在运行应用程序时会生成异常
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 中的 OnModelCreating 函数
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);
我不能只解决这个问题。
【问题讨论】:
标签: c# asp.net entity-framework linq-to-entities entity-framework-5