Tôi có một viewmodel mà cần dữ liệu từ hai mô hình người và địa chỉ:MVC4 C# Populating dữ liệu trong một viewmodel từ cơ sở dữ liệu
Models:
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 là như vậy
public class PersonAddViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Street { get; set; }
}
Tôi đã thử một số cách để lấy dữ liệu vào viewmodel và chuyển nó vào khung nhìn. Sẽ có nhiều bản ghi được trả lại để hiển thị.
phương pháp mới nhất của tôi là Populating mô hình điểm như vậy:
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());
}
tôi nhận được một lỗi trên địa chỉ Địa chỉ = db ... dòng "EntityCommandExecutionException là unhandled bởi mã người dùng
thế nào. bạn có thể cư một mô hình quan điểm với nhiều hồ sơ và chuyển cho một cái nhìn
giải pháp cuối cùng:?
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);
}
.210
là gì 'db' trong trường hợp này? Và thông điệp của ngoại lệ là gì? Bạn đang sử dụng Entity Framework hoặc LinqToSql? Bất cứ điều gì 'db' dường như gặp sự cố khi thực hiện lệnh để truy xuất dữ liệu nhưng không có thêm thông tin, nó có thể là bất cứ điều gì. –
@Brian S Tôi đang sử dụng khung pháp nhân. db là ngữ cảnh. – Xaxum
Tại sao bạn không sử dụng các thuộc tính điều hướng? – lahsrah