我收到一个我无法找到解决方案的错误,这很可能是我试图连接的模型的问题,我得到的错误如下:“类型'系统的例外.ArgumentOutOfRangeException'发生在mscorlib.dll中但在用户代码中没有处理“当我尝试遍历每一列时。所以基本上其中一个表的记录少于其他表?我该如何解决这个问题?迭代在视图中 - > item.Contacts.Count()
该程序应该从表中选择一些列:Contatti,Contacts和公司,它们位于不同的位置并将它们组合在一起(发生在控制器中的GET方法列表中),Contatti是一个sql server表导入到项目中的表为.edmx,另外2个是项目种子表的本地。代码如下:
将表格组合在一起的模型:
c
联系型号:
public partial class ContactsUni2
{
[Key, ForeignKey("Contatti")]
public int ContattoID { get; set; }
public List<Contatti> Contattis { get; set; }
public List<Companies> Companies { get; set; }
public List<Contact> Contacts { get; set; }
public virtual Contatti Contatti { get; set; }
public virtual Contact Contact { get; set; }
public virtual Companies Company { get; set; }
}
公司型号:
public class Contact
{
[Key]
public int ContactId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[ForeignKey("Companies")]
public int CompanyId { get; set; }
public virtual ICollection<Companies> Companies { get; set; }
[Required]
//public virtual Contatti Contatti { get; set; }
public virtual ICollection<Contatti> Contatti { get; set; }
}
康塔蒂模型:
public class Companies
{
[Key]
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public string CompanyAddress { get; set; }
public string CompanyCity { get; set; }
public string CompanyState { get; set; }
public string CompanyZip { get; set; }
public string CompanyArea { get; set; }
}
控制器GET:
public partial class Contatti
{
[Key, ForeignKey("Contact")]
public int ContattoID { get; set; }
public string Nome { get; set; }
public string Via { get; set; }
public string Citta { get; set; }
public string Stato { get; set; }
public string CodicePostale { get; set; }
public string Email { get; set; }
[Required]
public virtual ICollection<Contact> Contact { get; set; }
}
查看:
// GET: ContactsUni21
public ActionResult Index(String Page)
{
ContactsUni2 CU = new ContactsUni2();
CU.Contattis = db.Contattis.ToList();
CU.Contacts = db.Contacts.ToList();
CU.Companies = db.Companies.ToList();
List<ContactsUni2> contactlist = new List<ContactsUni2>();
contactlist.Add(CU);
return View(contactlist);
}
答案 0 :(得分:0)
我没有机会检查这个,但是这样的话:
@foreach (var item in Model.ToList())
{
//for (int i = 0; i < @item.Contacts.Count(); i++)
foreach (var contact in item)
{
<tr>
<td>
@contact.ContattoID
@contact.Nome
@contact.Citta
@contact.CodicePostale
@contact.Email
@contact.Address
@contact.CompanyId
@contact.ContactId
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ContattoID }) |
@Html.ActionLink("Details", "Details", new { id = item.ContattoID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ContattoID })
</td>
</tr>
}
}