gpt4 book ai didi

c# - MVC4 C# 从数据库中填充 View 模型中的数据

转载 作者:太空狗 更新时间:2023-10-29 23:00:17 24 4
gpt4 key购买 nike

我有一个 View 模型需要来自两个模型人和地址的数据:

模型:

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; }
}

我已经尝试了几种方法来将数据放入 View 模型并将其传递给 View 。会有多条记录返回显示。

我最新的方法是这样填充 View 模型:

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());
}

我在“EntityCommandExecutionException 未被用户代码处理”的 Address address = db... 行中收到错误。

如何使用多个记录填充 View 模型并传递给 View ?

最终解决方案:

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);
}

最佳答案

首先,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; }
}

然后你会简单地说:

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());
}

关于c# - MVC4 C# 从数据库中填充 View 模型中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16071531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com