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

Adding data to an existing model with real data to MVC

我之前有一个问题显示了我的模型的外观并且它添加了假数据。 Add to Existing Model based on a POCO with need to add to List<T>

现在我想添加真实的数据,我想知道如何做到这一点。我应该或需要循环遍历 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"},
   };


}

给定 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();

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

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

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