【发布时间】:2013-04-10 21:26:56
【问题描述】:
我有一个视图模型,它需要来自两个模型人员和地址的数据:
型号:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int Gender { get; set; }
}
public class Address
{
public int Id { get; set; }
public string Street { get; set; }
public int Zip { get; set; }
public int PersonId {get; set; }
}
Viewmodel 就是这样
public class PersonAddViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Street { get; set; }
}
我尝试了几种方法将数据导入视图模型并将其传递给视图。将有多个记录返回显示。
我的最新方法是这样填充视图模型:
private AppContexts db = new AppContexts();
public ActionResult ListPeople()
{
var model = new PersonAddViewModel();
var people = db.Persons;
foreach(Person p in people)
{
Address address = db.Addresses.SingleOrDefault(a => a.PersonId == p.Id)
model.Id = p.Id;
model.Name = p.Name;
model.Street = address.Street;
}
return View(model.ToList());
}
我在 Address address = db... 行出现错误“EntityCommandExecutionException is unhandled by user code。
如何使用多条记录填充视图模型并将其传递给视图?
最终解决方案:
private AppContexts db = new AppContexts();
private AppContexts dbt = new AppContexts();
public ActionResult ListPeople()
{
List<PersonAddViewModel> list = new List<PersonAddViewModel>();
var people = db.Persons;
foreach(Person p in people)
{
PersonAddViewModel model = new PersonAddViewModel();
Address address = dbt.Addresses.SingleOrDefault(a => a.PersonId == p.Id)
model.Id = p.Id;
model.Name = p.Name;
model.Street = address.Street;
}
return View(list);
}
【问题讨论】:
-
在这种情况下
db是什么?异常的信息是什么?您使用的是实体框架还是 LinqToSql?无论db是什么似乎都无法执行命令来检索数据,但如果没有更多信息,它可能是任何东西。 -
@Brian S 我正在使用实体框架。 db 是上下文。
-
你为什么不使用导航属性?
-
@sylon 我不太清楚导航属性是什么意思?我查了一下,发现在我的地址模型中的公共虚拟人员人员中会是这样的吗?
-
@Xaxum 给我们提供异常的详细信息?
标签: c# asp.net-mvc-4 viewmodel