当IEnumerable在模型中时,如何获取IEnumerable <t>中项目的属性

时间:2017-01-06 20:31:07

标签: c# asp.net-mvc entity-framework linq razor

我有以下模型,它有一个IEnumerable,其中T是另一个对象/模型:

public class Employee
{

    public ApplicationUser PayrollAdmin { get; set; }

    [Required]
    public int EmployeeId { get; set; }

    [Required]
    [DisplayName("First Name")]
    public string FirstName { get; set; }

    [Required]
    [DisplayName("Last Name")]
    public string LastName { get; set; }

    public virtual ICollection<Dependant> Dependants { get; set; }

}

Dependent类基本上是这样的:

public class Dependant
{

    public int DependantId { get; set; }

    [Required]
    [DisplayName("First Name")]
    public string FirstName { get; set; }
    [Required]
    [DisplayName("Last Name")]
    public string LastName { get; set; }

    [ForeignKey("Employee_EmployeeId")]
    public virtual Employee Employee { get; set; }

    public int? Employee_EmployeeId { get; set; }
}

我无法从Employee模型访问Dependent属性。剃刀不会暴露这些属性。我本质上想做像@ Model.Employee.Dependant.FirstName这样的东西但不能钻进那些属性。这是不可能的还是我需要做些什么来实现目标?

2 个答案:

答案 0 :(得分:3)

Dependants属性是一个集合,因此您需要对其进行迭代才能分别访问此集合的元素:

@foreach (var dependent in Model.Employee.Dependants)
{
    <div>@dependant.FirstName</div>
    <div>@dependant.LastName</div>
}

答案 1 :(得分:0)

Dependants是一个集合。你要么必须迭代:

@foreach (var item in Model.Employee.Dependants)
{
    <span>@item.FirstName @item.LastName</div>
}

或使用LINQ

@if(Model.Employee.Dependants.Any())
{
    Model.Employeee.Dependants.FirstOrDefault().FirstName
}