ASP.NET MVC 3:处理列表列表的 ViewModel

发布于 2024-10-27 16:29:04 字数 170 浏览 2 评论 0原文

我正在尝试组合一个 ViewModel,该 ViewModel 将具有用户列表,并且每个用户将具有位置列表。 用户表和位置表通过另一个表连接在一起,该表保存各自的 ID 和一些其他信息。该表本质上是一个多对多连接表。 我尝试了几种不同的 viewModel 方法,但我们严重缺乏它们......显示此类信息的最佳方法是什么?

I'm trying to put together a ViewModel that will have a list of users and each user will have a list of locations.
The User table and Location table are joined together through another table that holds each respective ID and some other information. This table is essentially a many to many join table.
I've tried a few different viewModel approaches and they we're severely lacking... What would be the best approach for displaying this type of information?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柏林苍穹下 2024-11-03 16:29:04

我假设问题是您希望能够通过用户或位置访问集合。一种方法是使用 ILookup 类。您将从多对多集合开始并生成如下查找:

var lookupByUser = userLocations.ToLookup(ul => ul.User);
var lookupByLocation = userLocations.ToLookup(ul => ul.Location);

更新:

根据您的描述,似乎您实际上并不需要拥有完整的多对多ViewModel 中的关系。相反,您的 ViewModel 可以具有如下结构:

public class YourViewModel
{
    public IEnumerable<UserViewModel> Users { get; set; }
}

public class UserViewModel
{
    // User-related stuff

    public IEnumerable<LocationViewModel> Locations { get; set; }
}

如果您想避免冗余 LocationViewModel 对象,您可以在 Model 和 ViewModel 对象之间预先构建映射:

var locationViewModels = myLocations.ToDictionary(
    loc => loc, loc => CreateLocationViewModel(loc));

然后在填充页面的视图模型。

I assume that the issue is that you want to be able to access the collection by either User or Location. One approach could be to use ILookup<> classes. You'd start with the many-to-many collection and produce the lookups like this:

var lookupByUser = userLocations.ToLookup(ul => ul.User);
var lookupByLocation = userLocations.ToLookup(ul => ul.Location);

Update:

Per your description, it seems like you don't really need to have a full many-to-many relationship in your ViewModel. Rather, your ViewModel could have a structure like this:

public class YourViewModel
{
    public IEnumerable<UserViewModel> Users { get; set; }
}

public class UserViewModel
{
    // User-related stuff

    public IEnumerable<LocationViewModel> Locations { get; set; }
}

If you wanted to avoid redundant LocationViewModel objects, you could pre-build a mapping between your Model and ViewModel objects:

var locationViewModels = myLocations.ToDictionary(
    loc => loc, loc => CreateLocationViewModel(loc));

And then reuse these objects when populating your page's ViewModel.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文