gpt4 book ai didi

asp.net-mvc - ASP.Net MVC 你在哪里从实体转换到 View 模型?

转载 作者:行者123 更新时间:2023-12-04 20:58:48 25 4
gpt4 key购买 nike

标题几乎解释了这一切,这是我尝试在我们的项目中工作的最后一件事。我们的结构是一个服务库,其中包含这样的功能。

        /// <summary>
/// Returns a single category based on the specified ID.
/// </summary>
public Category GetCategory(int CategoryID)
{
var RetVal = _session.Single<Category>(x => x.ID == CategoryID);
return RetVal;
}

现在 Category 是一个实体(我们正在使用 Entity Framework ),我们需要将其转换为 CategoryViewModel。

现在,人们将如何构建它?你会确保服务函数返回一个 CategoryViewModel 吗?让 Controller 从服务中提取数据然后调用另一个函数来转换到 View 模型?

最佳答案

这是 blog post 的摘录我写:

[AutoMap(typeof(IEnumerable<User>), typeof(IEnumerable<UserViewModel>))]
public ActionResult Index()
{
// return all users
IEnumerable<User> users = Repository.GetUsers();
return View(users);
}

在这种情况下,相应的 View 被强类型化为 IEnumerable<UserViewModel> .它使用 AutoMapper定义实体和 View 模型之间的转换规则。至于 [AutoMap]属性,它是一个自定义操作过滤器,它检查传递给 View 的模型并应用适当的转换,以便 View 只有 View 模型。

关于asp.net-mvc - ASP.Net MVC 你在哪里从实体转换到 View 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3004653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com