Xax*_*xum 5 c# viewmodel asp.net-mvc-4
我有一个viewmodel需要来自两个模型人和地址的数据:
楷模:
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; }
}
Run Code Online (Sandbox Code Playgroud)
Viewmodel就是这样
public class PersonAddViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Street { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了几种方法将数据导入viewmodel并将其传递给视图.将返回多个记录显示.
我的最新方法是填充视图模型:
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());
}
Run Code Online (Sandbox Code Playgroud)
我在地址address = db ...行上出现错误"EntityCommandExecutionException未被用户代码处理.
如何使用多个记录填充视图模型并传递给视图?
最终解决方案
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);
}
Run Code Online (Sandbox Code Playgroud)
首先,EntityCommandExecutionException错误表示实体上下文或实体本身的定义中存在错误.这是一个异常,因为它发现数据库与你告诉它的方式不同.你需要弄清楚那个问题.
其次,关于正确的方法,如果正确配置了上下文,那么您显示的代码应该可以正常工作.但是,更好的方法是使用导航属性,只要您想获取所有相关记录而不指定其他Where子句参数.导航属性可能如下所示:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int Gender { get; set; }
public virtual Address Address { get; set; }
// or possibly, if you want more than one address per person
public virtual ICollection<Address> Addresses { 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; }
public virtual Person Person { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后你会简单地说:
public ActionResult ListPeople()
{
var model = (from p in db.Persons // .Includes("Addresses") here?
select new PersonAddViewModel() {
Id = p.Id,
Name = p.Name,
Street = p.Address.Street,
// or if collection
Street2 = p.Addresses.Select(a => a.Street).FirstOrDefault()
});
return View(model.ToList());
}
Run Code Online (Sandbox Code Playgroud)