0

我正在努力解决人际关系,我希望有人可以为我澄清这一点。

我有以下两种型号

public class dsExpressionOfInterest
{
    public int dsExpressionOfInterestID { get; set; }

    [Display(Name = "Customer Name")]
    public string CustomerName { get; set; }

    public virtual dsRegistration dsRegistration { get; set; }
}

public class dsRegistration
{
    public int dsRegistrationID { get; set; }

    [Display(Name = "Expression Of Interest ID")]
    public int dsExpressionOfInterestID { get; set; }

    [Display(Name = "SLA Received")]
    public bool SLAReceived { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Date Received")]
    public DateTime? SLAReceivedDate { get; set; }
}

在 dsRegistration 的索引视图中,我希望能够显示 dsExpressionOfInterest 中的 CustomerName 字段,但是这对我不可用。

应该如何设置我的导航属性以促进这一点?

更新

我的控制器

public ActionResult Index()
{
    var dsregistration = db.dsRegistration.Include(d => d.Employee).Where(d => d.PackSent == false);

    return View(dsregistration);
}

为了简化问题,我没有在上述模型中显示其他附加字段。

4

2 回答 2

1

假设这是一对一的关系,则设置错误

我假设每个Registration 都有一个ExpressionOfInterest,并且每个ExpressionOfInterest 都只有一个Registration。

为了在 MVC4 中建立一对一的关系,孩子的主键也必须是外键。关系应如下所示:

public class dsRegistration
{
    public int dsRegistrationID { get; set; }

    [Display(Name = "SLA Received")]
    public bool SLAReceived { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Date Received")]
    public DateTime? SLAReceivedDate { get; set; }

    //Indicate that a dsRegistration has an expresison of interest
    public dsExpressionOfInterest expressionOfInterest { get; set;}
}

public class dsExpressionOfInterest
{
    //Foreign key
    [Key, ForeignKey("dsRegistration")]
    public int dsExpressionOfInterestID { get; set; }

    [Display(Name = "Customer Name")]
    public string CustomerName { get; set; }

    public virtual dsRegistration dsRegistration { get; set; }
}

现在在你的控制器中你应该可以使用

var dsregistration = db.dsRegistration.Include("dsExpressionOfInterest").Where(d => d.PackSent == false);

最后,在视图中您应该能够访问registration.expressionOfInterest.CustomerName

于 2013-07-10T14:09:59.110 回答
1

制作一个不同于您通常的域模型的 ViewModel。ViewModel 应该包含视图所需的字段。对于每个操作,您可能会有不同的 ViewModel。例如,如果操作名为 Index:

public class RegistrationIndexViewModel
{
    public int dsRegistrationID { get; set; }

    [Display(Name = "Expression Of Interest ID")]
    public int dsExpressionOfInterestID { get; set; }

    [Display(Name = "SLA Received")]
    public bool SLAReceived { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Date Received")]
    public DateTime? SLAReceivedDate { get; set; }

    [Display(Name = "Customer Name")]
    public string CustomerName { get; set; }
}

您将视图模型传递给 dsRegistration 视图而不是域模型。域模型与数据库一起工作并强制执行业务逻辑。视图模型被传递给视图。

于 2013-07-10T13:47:14.643 回答