【问题标题】:Assign the result of Navigation Property to View Model将 Navigation Property 的结果分配给 View Model
【发布时间】:2018-01-13 09:08:48
【问题描述】:

这是我的数据库架构:-

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 Property 做到这一点?我只是误解了它的用法吗?

【问题讨论】:

    标签: c# entity-framework viewmodel code-first


    【解决方案1】:

    我发现实际上在我的架构中没有导航属性。要拥有 导航属性,您的类中必须有 Constructor 和引用该构造函数的 ForeignKey

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多