代码第一个外键

时间:2013-05-21 15:23:01

标签: asp.net-mvc razor code-first

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

我不确定如何首先使用代码创建Initiator和Owner外键,以及如何使用razor显示FullName。

有什么想法吗?感谢。

ChangeRequest

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)
}

1 个答案:

答案 0 :(得分:0)

你没有提到EF版本,如果你想延迟加载,或者你正在使用属性或Fluent api,那么这里是一个很好的参考多值关联using 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)
}