.NET MVC relationships
本文关键字:relationships MVC NET | 更新日期: 2023-09-27 18:21:45
我正试图理清关系,希望有人能帮我澄清这一点。
我有以下两种型号的
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);
}
为了简化问题,我在上面的模型中没有显示其他额外的字段。
假设这是一对一的关系,则设置错误。
我假设每个注册都有一个意向书,每个意向书也有一个注册。
为了在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
创建一个不同于常规域模型的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视图,而不是域模型。域模型与数据库一起工作,并强制执行业务逻辑。视图模型将传递给视图。