我已经创建了一个视图模型,我需要连接到一个知识库模型。我以前已经将视图模型与模型连接过,但是在这种情况下,intellisense对于结果并没有显示出知识库模型的任何字段。下面是我正在尝试的代码:
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下面所建议的,我安装了自动程序,并在我的应用程序启动中设置了它。然而,在这一行上:
List<KnowledgebaseResult> knowledgebaseResults = Mapper.Map<KnowledgebaseResult>(model.ToList());
他说,我正在得到错误,“不能隐式地将knowledgebaseResult转换为list。
我遗漏了什么?
发布于 2015-07-21 14:44:38
您正在尝试访问单个模型的单个属性,尽管您正在与列表进行交互。为了映射您的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));
https://stackoverflow.com/questions/31541984
复制相似问题