【问题标题】:Entity Framework --Unable to determine the principal end of an association between the types?实体框架——无法确定类型之间关联的主体端?
【发布时间】: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


【解决方案1】:

如果您想要 1 : 1 的关系,您必须删除 [ForeignKey("ProjectId")] 属性。对于 1:1 关系,使用主键。如果你想要一个单独的外键列,它是一个 1 : * 关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 2013-05-26
    • 1970-01-01
    相关资源
    最近更新 更多