Asp.net mvc 在asp.net mvc中为具有一对多关系的模型创建视图模型
我创建了两个模型名为Company和Agent,它们之间应该有一对多的关系,因为每个公司可以有多个Agent,但每个Agent都与一个公司相关。这些模式如下:Asp.net mvc 在asp.net mvc中为具有一对多关系的模型创建视图模型,asp.net-mvc,entity-framework,Asp.net Mvc,Entity Framework,我创建了两个模型名为Company和Agent,它们之间应该有一对多的关系,因为每个公司可以有多个Agent,但每个Agent都与一个公司相关。这些模式如下: Public class Company { Public int ComapnyId {get;set;} Public String CompanyName{get;set;} Public String tell{get;set;} Public String Address{get;
Public class Company
{
Public int ComapnyId {get;set;}
Public String CompanyName{get;set;}
Public String tell{get;set;}
Public String Address{get;set;}
Public virtual ICollection<Agent> Agents {get;set;}
}
Public Class Agent
{
Public int AgentId{get;set;}
public string FName{get;set;}
public string LName{get;set;}
public string Mobile{get;set;}
public int? CompanyId{get;set;}
[ForeignKey("CompanyId")]
public virtual Company company{get;set;}
}
上市公司
{
公共int ComapnyId{get;set;}
公共字符串CompanyName{get;set;}
公共字符串tell{get;set;}
公共字符串地址{get;set;}
公共虚拟ICollection代理{get;set;}
}
公共类代理
{
公共int代理{get;set;}
公共字符串FName{get;set;}
公共字符串LName{get;set;}
公共字符串Mobile{get;set;}
公共int?CompanyId{get;set;}
[外键(“公司ID”)]
公共虚拟公司公司{get;set;}
}
然后我创建视图模型,如下所示,但我不确定是否正确定义了它们以满足我的目标
public Class CompanyViewModel
{
Public int ComapnyId {get;set;}
Public String CompanyName{get;set;}
Public String tell{get;set;}
Public String Address{get;set;}
Public List<AgentViewModel> AgentsName {get;set;}
}
Public AgentViewModel
{
Public int AgentId{get;set;}
public string FName{get;set;}
public string LName{get;set;}
public string Mobile{get;set;}
public int? CompanyId{get;set;}
[ForeignKey("CompanyId")]
public string CompanyName{get;set;}
}
公共类公司视图模型
{
公共int ComapnyId{get;set;}
公共字符串CompanyName{get;set;}
公共字符串tell{get;set;}
公共字符串地址{get;set;}
公共列表代理名称{get;set;}
}
公共代理视图模型
{
公共int代理{get;set;}
公共字符串FName{get;set;}
公共字符串LName{get;set;}
公共字符串Mobile{get;set;}
公共int?CompanyId{get;set;}
[外键(“公司ID”)]
公共字符串CompanyName{get;set;}
}
事实上,当用户想要创建一个代理时,我希望在下拉列表中向他显示所有公司。关于它我有很多问题,但第一个问题是它的两个性质
Public List<AgentViewModel> AgentsName {get;set;} and
public string CompanyName{get;set;}
公共列表代理名称{get;set;}和
公共字符串CompanyName{get;set;}
是否在viewmodels中为我的目标正确定义?否,很遗憾,您没有正确执行此操作。因此,您成功地创建了两个基本上与模型类重复的新类,并更改了名称以包含单词viewmodel 在本例中,您应该做的只是将视图传递给一个新的代理模型,并在viewBag中设置一个不同的公司列表(强制转换到selectListItems中),以用作选择下拉列表,在代理模型上设置CompanyId的值 根据您描述的确切需求,没有理由创建视图模型