繁体   English   中英

实体框架代码优先关系

[英]Entity Framework Code First Relationships

我正在使用Code First学习EF,但在正确建立关系方面遇到很多麻烦。

简单的员工

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

一个简单的项目

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

在项目上花费的时间

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

我正在尝试在EmployeeID上加入Employee to Time,在ProjectID上加入Project to Time,我只是不明白EF如何确定关系。 我正在尝试使用数据注释来定义关系。 我尝试使用ForeignKey批注定义关系,但是也没有用。

我将运行的内容,但是在Project表上,将创建一个名为Project_ProjectID的新字段,如果尝试在VS中运行查询,则会收到一条错误消息,指出Time_TimeID列无效(它是...)。 有人可以帮我了解我在做什么错吗?

您不需要DataAnnotations,因为在这种情况下约定对您有用

尝试以下

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
}

本文可能会有所帮助http://msdn.microsoft.com/zh-CN/data/jj679962.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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