简体   繁体   中英

Entity Framework Code First Relationships

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...). Can someone please help me understand what I'm doing wrong?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM