0

I am creating entities using code first schema but when run the application its generating exception

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.

My scenario is to implement 1.1 relation between Projects and DateOfProjects such that 1 project has 1 dateOfProject.

My code is

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


    }

and inside DbContextClass inOnModelCreating function

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

I could not just resolve that problem.

Hassaan
  • 3,931
  • 11
  • 34
  • 67
  • possible duplicate of [Unable to determine the principle end of an association](http://stackoverflow.com/questions/20035021/unable-to-determine-the-principle-end-of-an-association) – Colin Jun 24 '14 at 13:50

1 Answers1

0

If you want a 1 : 1 relationship you have to remove the [ForeignKey("ProjectId")] Attribute. For 1: 1 relationships the Primary Key is used. If you want a separate foreign Key column it is a 1 : * relationship.

codeworx
  • 2,715
  • 13
  • 12