I have just started learning MVC 5 and the Entity Framework as well as using the Identity Model.
I am trying to add an additional property to the ApplicationUser
Model that is a list of Customers. Basically, a user can have many Customers attached to their login.
I seem to have it at least displaying the list of customers on the Register.cshtml page, however I am unsure if this is the best way to do this.
In my RegisterViewModel.cs
, I have added the below:
[Display(Name = "Customer List")]
public IEnumerable<Customer> Customers { get; set; }
Then in my AccountController
, I have added to get a list of customers and pass this to the ViewModel:
private GatewayContext gatewayContext = new GatewayContext();
var customers = gatewayContext.Customers.ToList();
var viewModel = new RegisterViewModel();
viewModel.Customers = customers;
return View(viewModel);
Is this the correct way of doing this? My worry is that I have created the gatewayContext
as a property of the AccountController
and not sure if this is the correct way of going about it.
Sorry if the question is a bit ambigious. I can reword if necessary! I just want to make sure I am building my application in the correct way.
You're on the right track with the RegisterViewModel change.
However, it is better to use your DbContext
within the controller method:
public ActionResult Register(...)
{
List<Customer> customers;
using (GatewayContext db = new GatewayContext())
{
customers = db.Customers.ToList();
}
var viewModel = new RegisterViewModel();
viewModel.Customers = customers;
return View(viewModel);
}
The idea here being to use and dispose of the context as quickly as possible. This helps by returning the Sql Server connection to the connection pool sooner, which means less waiting for a connection for other simultaneous requests.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다