将真实数据添加到MVC中,将数据添加到现有模型中 [英] Adding data to an existing model with real data to MVC
问题描述
我有一个先前的问题,该问题显示了我的模型的外观以及是否添加了FAKE数据. 添加到现有列表需要添加到List< T>
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>
现在,我想添加REAL数据,我想知道如何执行此操作.我应该还是需要遍历result
??
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"},
};
}
推荐答案
给出Person模型
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();
然后将collection属性分配给另一个模型
Then assign the collection property to another model
var model = new ResultViewModel
{
...
findPersonResultsViewModel = result
};
如果您要返回IEnumerable,请执行.ToList()
来获取List<T>
.
If you're getting back IEnumerable, do .ToList()
to get the List<T>
.
这篇关于将真实数据添加到MVC中,将数据添加到现有模型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!