I have an Address View Model and I used to initialize the list of countries from the database in the view model creation, however I realized that each time I create the ViewModel somewhere, the list of countries is retrieved from the db without being used, so I though of three ways to do accomplish this:
我有一个地址视图模型,我曾经在视图模型创建中初始化数据库中的国家列表,但是我意识到每次在某处创建ViewModel时,都会从数据库中检索国家列表而不使用它,所以我有三种方法可以做到这一点:
- Add the Countries initialization to the Address View Model Constructor, very costly
- 将Countries初始化添加到Address View Model Constructor,非常昂贵
- Load the lookup from the controllers and then assign it to the view model and then load the view
- 从控制器加载查找,然后将其分配给视图模型,然后加载视图
-
Using lazy loading on the countries property, so the trip is made to the db only when the countries are required, something like this
在countries属性上使用延迟加载,因此只有在需要国家/地区时才会访问数据库,就像这样
// Lazy loading [ScriptIgnore] private IEnumerable<SelectListItem> _Countries; [ScriptIgnore] public IEnumerable<SelectListItem> Countries { get{ if (_Countries.Count() > 0) return _Countries; else { using (var db = new AllegroDMContainer()) { var rCountries = db.Countries.ToList(); _Countries = (from m in rCountries select new SelectListItem { Text = m.Name + " (" + m.ISO + ")", Value = m.ID.ToString() }); return _Countries; } } } set{ _Countries = value; } }
What do you guys think is the better approach here and the one that seems more natural?
你们认为这里更好的方法和看起来更自然的方法是什么?
1 个解决方案
#1
1
- Add the Countries initialization to the Address View Model Constructor, very costly
- 将Countries初始化添加到Address View Model Constructor,非常昂贵
This is fine, assuming that you're passing a collection and not a DbContext.
假设您传递的是集合而不是DbContext,这很好。
- Load the lookup from the controllers and then assign it to the view model and then load the view
- 从控制器加载查找,然后将其分配给视图模型,然后加载视图
This is the most common pattern I've seen.
这是我见过的最常见的模式。
- Using lazy loading on the countries property, so the trip is made to the db only when the countries are required, something like this
- 在countries属性上使用延迟加载,因此只有在需要国家/地区时才会访问数据库,就像这样
This couples the ViewModel to the DAL, which is a bad thing. Don't do this.
这将ViewModel耦合到DAL,这是一件坏事。不要这样做。
#1
1
- Add the Countries initialization to the Address View Model Constructor, very costly
- 将Countries初始化添加到Address View Model Constructor,非常昂贵
This is fine, assuming that you're passing a collection and not a DbContext.
假设您传递的是集合而不是DbContext,这很好。
- Load the lookup from the controllers and then assign it to the view model and then load the view
- 从控制器加载查找,然后将其分配给视图模型,然后加载视图
This is the most common pattern I've seen.
这是我见过的最常见的模式。
- Using lazy loading on the countries property, so the trip is made to the db only when the countries are required, something like this
- 在countries属性上使用延迟加载,因此只有在需要国家/地区时才会访问数据库,就像这样
This couples the ViewModel to the DAL, which is a bad thing. Don't do this.
这将ViewModel耦合到DAL,这是一件坏事。不要这样做。