Adding data to an existing model with real data to MVC

泪湿孤枕 提交于 2019-12-25 01:14:30

问题


I have a previous question that shows how my models look and it was adding FAKE data. Add to Existing Model based on a POCO with need to add to List<T>

Now I am wanting to add REAL data and i'm wondering how to do this. Should or need I loop over the 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:


Given the Person model

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

And you obtain the result from your context

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

You need a collection of a different but similar type, so you use a projection

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

Then assign the collection property to another model

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

If you're getting back IEnumerable, do .ToList() to get the List<T>.



来源:https://stackoverflow.com/questions/56552454/adding-data-to-an-existing-model-with-real-data-to-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!