将 Navigation 属性 的结果分配给 View Model

Assign the result of Navigation Property to View Model

这是我的数据库模式:-

public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Employee> Employee_Id { get; set; }
}

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public long Salary { get; set; }
    public string Gender { get; set; }
    public virtual Department Department_Id { get; set; }
}

根据我的研究,使用 View Models 是一种很好的做法,所以我通常使用这种查询来创建我的模型:-

var v = edm.Departments.Select(x => new departmentViewModel { Name = x.Name });
return v.ToList();

现在我想将 导航 属性 的好处添加到我的代码中。问题是如果我不能将结果分配给我的 View Model,它对我没有用。如果我尝试通过 Employee 访问 Department,我无法访问 .Select()声明。

var v = edm.Employees.Where(x => x.Id == 1).FirstOrDefault().Department_Id. //Ops!!!

在上面的语句中我可以访问 IdName 但是 .Select() 是不可访问的。

我可以忽略 导航 属性 并将我的查询分成两个查询并实现我想要的。但是我想问我如何使用 Navigation 属性 来做到这一点?我只是误解了它的用法吗?

我发现实际上在我的模式中没有导航属性。要使用 Navigation 属性,您的 类 和 ForeignKey[=25 中必须有 Constructor =] 引用该构造函数。

public class Department
{
    public Department(){} //needed constructor

    public int Id { get; set; }
    public string Name { get; set; }

    [ForeignKey("Employee")]
    public int Employee_Id;
    public virtual ICollection<Employee> Employee { get; set; }
}

public class Employee
{
    public Employee(){} //needed constructor

    public int Id { get; set; }
    public string Name { get; set; }
    public long Salary { get; set; }
    public string Gender { get; set; }

    [ForeignKey("Department")]
    public int Department_Id;
    public virtual Department Department { get; set; }
}

现在我可以通过 Employee 以标准方式访问 Department.Select( ) 语句仍然无法访问。这并不重要,我发现我可以将结果复制到下一行的 View Model 而无需 .Select()声明。

var e = edm.Employees.Where(x => x.Id == 1).FirstOrDefault().Department; //.select() is still inaccessible
departmentViewModel department = new departmentViewModel() { Id = e.Id, Name = e.Name };//but I could copy the result into my View Model here