Question

I'm learning EF using Code First and I'm having a lot of trouble getting my relationships to build correctly.

A Simple Employee

public class Employee
{
    [Key]
    public int EmployeeId { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
}

A Simple Project

public class Project
{
    [Key]
    public int ProjectId { get; set; }
    public String ProjectNumber { get; set; }
}

The time spent on the project

public class Time
{
    [Key]
    public int TimeId { get; set; }
    public int EmployeeID { get; set; }
    public String ProjectID { get; set; }
    public long? TimeSpent { get; set; }
    
    public virtual Employee Employee { get; set; }
    public virtual Project Project { get; set; }
}

I'm trying to join Employee to Time on EmployeeID and join Project to Time on ProjectID and I just don't understand how EF determines relationships. I'm trying to use Data Annotations to define the relationships. I've tried using the ForeignKey annotation to define the relationships but that has not worked either.

What I have will run, but on the Project table, a new field named Project_ProjectID is created and if I try to run a query in VS I get an error saying that the column Time_TimeID is invalid (which it is). What am I doing wrong?

Was it helpful?

Solution

You shouldn't need DataAnnotations as conventions will work for you in this case

Try the following

public class Time
{
    [Key]
    public int TimeId { get; set; }
    public int EmployeeID { get; set; }
    public int ProjectID { get; set; }  //<< Changed type from string
    public long? TimeSpent { get; set; }

    public virtual Employee Employee { get; set; }
    public virtual Project Project { get; set; }
}

public class Employee
{
    [Key]
    public int EmployeeId { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }

    // Set up the other side of the relationship
    public virtual ICollection<Time> Times { get; set; } // << Added
}

public class Project
{
    [Key]
    public int ProjectId { get; set; }
    public String ProjectNumber { get; set; }

    // Set up the other side of the relationship
    public virtual ICollection<Time> Times { get; set; } // << Added
}

This article may help http://msdn.microsoft.com/en-gb/data/jj679962.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top