将视图模型连接到一个接一个的模型

本文关键字:一个 模型 视图 连接 | 更新日期: 2023-09-27 18:03:53

我已经创建了一个视图模型,我需要连接到一个知识库模型。我之前已经将视图模型连接到模型,但是在这种情况下,对结果的智能感知并没有为知识库模型提供任何字段。下面是我正在尝试的代码:

   public ActionResult TechSearchKnowledgebase([Optional]Guid createdById, [Optional]Guid categoryId, [Optional]Guid typeId)
        {
            var model = db.Knowledgebases.AsQueryable();
            if (createdById != Guid.Empty)
            {
                model = model.Where(k => k.CreatedById == createdById);
                ViewBag.CreatedBy = db.Users.Where(c => c.UserId == createdById).First().FullName;
            }
            if (categoryId != Guid.Empty)
            {
                model = model.Where(k => k.CategoryId == categoryId);
                ViewBag.Category = db.Categories.Where(c => c.CategoryId == categoryId).First().CategoryName;
            }
            if (typeId != Guid.Empty)
            {
                model = model.Where(k => k.TypeId == typeId);
                ViewBag.Category = db.Roles.Where(c => c.RoleID == typeId).First().RoleDescription;
            }
            model=model.OrderBy(k => k.CreatedDate);
            var result=model.ToList();
            KnowledgebaseResult knowledgebaseResult = new KnowledgebaseResult();
            knowledgebaseResult.CategoryId = result.CategoryId;
            return View("TechKnowledgebaseList", result);
        }

根据Chris下面的建议,我安装了automapper并在我的应用程序启动中设置了它。但是,在这一行:

List<KnowledgebaseResult> knowledgebaseResults = Mapper.Map<KnowledgebaseResult>(model.ToList());

他建议,我得到错误,"不能隐式地转换knowledgebaseResult到列表。

我错过了什么?

将视图模型连接到一个接一个的模型

您正在尝试访问单个模型的单个属性,尽管您正在与列表交互。为了映射您的CategoryId,您需要循环遍历列表中的每个项目并建立关联。有一些库可以使这种映射更简洁,比如AutoMapper (http://automapper.org/)。

使用AutoMapper,您只需在两个对象之间创建一个映射,并传入一个数据源。

Mapper.CreateMap<Knowledgebase, KnowledgebaseResult>();

将上述内容放在配置文件中,它将在Application_Start上被调用。

List<KnowledgebaseResult> knowledgebaseResults = Mapper.Map<List<KnowledgebaseResult>>(model.ToList());

现在每个KnowledgebaseResult都是从原始模型映射出来的,假设所有属性都命名相同。如果没有,可以使用以下语法覆盖映射:

Mapper.CreateMap<Knowledgebase, KnowledgebaseReslt>().ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.KBId));