将真实数据添加到现有模型到MVC

时间:2019-06-11 22:32:32

标签: c# asp.net list asp.net-core viewmodel

我有一个先前的问题,它显示了我的模型的外观以及正在添加FAKE数据。 Add to Existing Model based on a POCO with need to add to List<T>

现在我要添加REAL数据,我想知道如何执行此操作。我应该还是需要遍历result

public IActionResult FindPerson (FindPersonViewModel findPersonViewModel)
{
    var firstName = findPersonViewModel.FirstName;
    var middleName = findPersonViewModel.MiddleName;
    var lastName = findPersonViewModel.LastName;
    var emailAddress = findPersonViewModel.EmailAddress;
    var genderTypeId = findPersonViewModel.GenderTypeId;


    // GET REAL DATA 
    using (AzEdsIdentityContext context = new AzEdsIdentityContext(AzEdsIdentityContext.Options))
    {
         var result = context.FindPerson(firstName, lastName, genderTypeId);

         // for loop on the result to hydrate new List<FindPersonResultsViewModel>()  ?         

    }


   // Note:  here is exactly how I hydrated the model with fake data

   findPersonViewModel.findPersonResultsViewModel = new List<FindPersonResultsViewModel>()
                { new FindPersonResultsViewModel { AZEDID = 33423432, PersonID = 3534454, FirstName = "John", LastName = "Williamson", MiddleName = "K", ExistInContactManager = false, ActionType = true, ContactType = "Principal", DOB = "5/1/1985", PhysicalAddress = "123 main st. mesa, az.", PreferredEmail = "john@aol.com", PreferredPhone = "602-393-4443"},
                  new FindPersonResultsViewModel { AZEDID = 33423432, PersonID = 3534454, FirstName = "Jon", LastName = "Williamson", MiddleName = "K", ExistInContactManager = false, ActionType = true, ContactType = "Principal", DOB = "5/1/1985", PhysicalAddress = "123 main st. mesa, az.", PreferredEmail = "john@aol.com", PreferredPhone = "602-393-4443"},
   };


}

1 个答案:

答案 0 :(得分:1)

给出Person模型

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

然后从上下文中获取结果

List<Person> result = context.getPersons();

您需要一个不同但相似类型的集合,因此您要使用投影

List<PersonViewModel> result =
    context.getPersons()
           .Select(p => new FindPersonResultsViewModel
                            {
                                Name = p.Name,
                                Email = p.Email
                            }).ToList();

然后将collection属性分配给另一个模型

var model = new ResultViewModel
                {
                    ...
                    findPersonResultsViewModel = result
                };

如果您要返回IEnumerable,请执行.ToList()以获取List<T>