0

在我看来,我需要为每个发起者和所有者返回 FullName。为此,Initiator 和 Owner 都应该是 EmployeeID 的外键吗?

我不确定如何首先使用代码创建发起者和所有者外键,也不确定如何使用剃刀显示全名。

有任何想法吗?谢谢。

改变请求

namespace Project.Models
{
    public class ChangeRequest
    {
        public int ChangeRequestID { get; set; }
        public int Initiator { get; set; }
        public int Owner { get; set; }
    }
}

员工

namespace Project.Models
{
    public class Employee
    {
        public int EmployeeID { get; set; }
        public string Surname { get; set; }
        public string FirstName { get; set; }

        public string FullName
        {
            get
            {
                return Surname + ", " + FirstName;
            }
        }
    }
}

看法

@foreach (var item in Model.ChangeRequests)
{
     @Html.DisplayFor(modelItem => item.Initiator)
     @Html.DisplayFor(modelItem => item.Owner)
}
4

1 回答 1

0

您还没有提到 EF 版本,如果您想要延迟加载,或者如果您正在使用属性或 Fluent api,那么这里有一个使用 Fluent API和一个使用DataAnnotations的多值关联的很好参考,以及一些示例代码制作一些关于版本、延迟加载和属性的假设:

public class ChangeRequest
{
    [Key]
    public int ChangeRequestID { get; set; }
    public int? InitiatorId { get; set; }
    public int? OwnerId { get; set; }

    [ForeignKey("InitiatorId")]
    public virtual Employee Initiator { get; set; }
    [ForeignKey("OwnerId")]
    public virtual Employee Owner { get; set; }
}
public class Employee
{
    [Key]
    public int EmployeeID { get; set; }
    public string Surname { get; set; }
    public string FirstName { get; set; }

    [InverseProperty("Initiator")]
    public virtual ICollection<ChangeRequest> CrsInitiated { get; set; }
    [InverseProperty("Owner")]
    public virtual ICollection<ChangeRequest> CrsOwned { get; set; }

    [NotMapped]
    public string FullName
    {
        get
        {
            return Surname + ", " + FirstName;
        }
    }
}

剃刀:

@foreach (var item in Model.ChangeRequests)
{
     @Html.DisplayFor(modelItem => item.Initiator.FullName)
     @Html.DisplayFor(modelItem => item.Owner.FullName)
}
于 2013-05-21T16:04:32.967 回答