Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 实体框架和关系有问题_C#_Asp.net Mvc_Entity Framework - Fatal编程技术网

C# 实体框架和关系有问题

C# 实体框架和关系有问题,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,我很难理解如何创建与实体框架的关系。(我正在使用MVC体系结构和代码优先迁移)例如,如果我有一个类 public class Employee { public int Id { get; set; } public string PIN { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } 我还有一门课,比如说,我希望跟踪员工的工作时

我很难理解如何创建与实体框架的关系。(我正在使用
MVC
体系结构和代码优先迁移)例如,如果我有一个类

public class Employee
{
    public int Id { get; set; }
    public string PIN { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
我还有一门课,比如说,我希望跟踪员工的工作时间

public class EmployeeHours
{
    public int Id { get; set; }
    public DateTime? ClockIn { get; set; }
    public DateTime? ClockOut { get; set; }
    public Employee emplyee { get; set; }
}
我很难理解如何让这两门课相互交流。例如,如果John Smith的PIN是
1234
,他将PIN输入文本框,我如何成功地将他的时钟时间和日期添加到employee hours类中

如果我有这样一个视图,员工可以输入他们的PIN

@using (Html.BeginForm("ClockIn", "Login")) 
{
    @Html.LabelFor(c => c.Employee.PIN)
    @Html.TextBoxFor(c => c.Employee.PIN)<br />

    <button type="submit">Save</button>
}
我试图弄清楚如何在类中存储与该员工相关的时间和日期,这样我就可以返回并查看该员工何时打卡。谢谢

向员工添加一个,例如:

public class Employee
{
    public int Id { get; set; }
    public string PIN { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<EmployeeHours> Hours { get; } = new HashSet<EmployeeHours>();
}

好吧,现在我的问题是它说emp是空的?我的employee表中保存了一个pin为1234的员工,但由于某种原因,每当我输入1234并按下按钮时,就会出现错误“对象引用未设置为对象的实例”。有什么建议吗?
public class Employee
{
    public int Id { get; set; }
    public string PIN { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<EmployeeHours> Hours { get; } = new HashSet<EmployeeHours>();
}
[HttpPost]
public ActionResult ClockIn(string pin)//employee clocking in
{
    var emp = _context.Employees.Where(e => e.Pin == pin).First();
    var hours = new EmployeeHours();
    hours.StartTime = DateTime.Now;
    //...
    emp.Hours.Add(hours);
    _context.SaveChanges();
    return View();
}