MVC4 C# 从数据库填充视图模型中的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16071531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:55:06  来源:igfitidea点击:

MVC4 C# Populating data in a viewmodel from database

c#asp.net-mvc-4viewmodel

提问by Xaxum

I have a viewmodel which needs data from two models person and address:

我有一个视图模型,它需要来自两个模型人和地址的数据:

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

The Viewmodel is as such

Viewmodel 就是这样

public class PersonAddViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Street { get; set; }
}

I have tried several ways to get data into the viewmodel and pass it to the view. There will be multiple records returned to display.

我尝试了多种方法将数据放入视图模型并将其传递给视图。将有多个记录返回显示。

My latest method is populating the view model as such:

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

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

I get an error on the Address address = db... line of "EntityCommandExecutionException was unhandled by user code.

我在“EntityCommandExecutionException was unhandled by user code.”的 Address address = db... 行上收到错误消息。

How can you populate a view model with multiple records and pass to a view?

如何使用多条记录填充视图模型并传递给视图?

Final Solution:

最终解决方案:

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

采纳答案by Erik Funkenbusch

First, EntityCommandExecutionException errors indicates an error in the definition of your entity context, or the entities themselves. This is throwing an exception because it's found the database to be different from the way you told it that it should be. You need to figure out that problem.

首先,EntityCommandExecutionException 错误表示实体上下文的定义或实体本身存在错误。这是抛出异常,因为它发现数据库与您告诉它应该的方式不同。你需要弄清楚那个问题。

Second, regarding the proper way to do this, the code you've shown should work if your context were correctly configured. But, a better way would be to use Navigational properties, so long as you want to get all related records and not specify other Where clause parameters. A navigational property might look like this:

其次,关于执行此操作的正确方法,如果您的上下文配置正确,您显示的代码应该可以工作。但是,更好的方法是使用 Navigational 属性,只要您想获取所有相关记录并且不指定其他 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; }
}

Then you would simply say:

然后你会简单地说:

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

回答by MattSull

For displaying lists of objects, you could use a generic view model that has a generic list:

为了显示对象列表,您可以使用具有通用列表的通用视图模型:

public class GenericViewModel<T>
{
    public List<T> Results { get; set; }

    public GenericViewModel()
    {
        this.Results = new List<T>();
    }
}

Have a controller action that returns, say all people from your database:

有一个返回的控制器操作,比如数据库中的所有人:

[HttpGet]
public ActionResult GetAllPeople(GenericViewModel<People> viewModel)
{
    var query = (from x in db.People select x); // Select all people
    viewModel.Results = query.ToList();

    return View("_MyView", viewModel);
}

Then make your view strongly typed, taking in your generic view model:

然后使您的视图强类型化,采用您的通用视图模型:

@model NameSpace.ViewModels.GenericViewModel<NameSpace.Models.People>