我对MVC和EF都是新手。遵循一些不错的教程,我终于创建了我的POCO类。
我正在尝试在分层架构中使用POCO类创建一个MVC模型。我的POCO类位于名为Entities的类库项目中。
我的MVC4应用程序是一个引用实体的Web项目。
我查询数据库并在实体中包含内容,并希望将3-4个POCO类映射到单个模型,这样我就可以创建一个强类型视图。
我不确定如何继续。在这件事上帮我。
发布于 2013-04-07 22:05:34
查看ASP.NET MVC in Action book.。它有一个完整的章节专门介绍这个主题。他们建议并展示了如何使用AutoMapper将领域实体映射到ViewModels。
我还有一个here示例。
在BootStrapper中:
Mapper.CreateMap<Building, BuildingDisplay>()
.ForMember(dst => dst.TypeName, opt => opt.MapFrom(src => src.BuildingType.Name)); 在控制器中:
public ActionResult Details(int id)
{
var building = _db.Buildings.Find(id);
if (building == null)
{
ViewBag.Message = "Building not found.";
return View("NotFound");
}
var buildingDisplay = Mapper.Map<Building, BuildingDisplay>(building);
buildingDisplay.BinList = Mapper.Map<ICollection<Bin>, List<BinList>>(building.Bins);
return View(buildingDisplay);
} 发布于 2013-04-07 22:09:18
我以前已经回答过这样的问题一次,如果你想看,这里是链接
http://stackoverflow.com/questions/15432246/creating-a-mvc-viewmodels-for-my-data/15436044#15436044但是如果你需要更多的帮助,请告诉我:D这是你的视图模型
public class CategoryViewModel
{
[Key]
public int CategoryId { get; set; }
[Required(ErrorMessage="* required")]
[Display(Name="Name")]
public string CategoryName { get; set; }
[Display(Name = "Description")]
public string CategoryDescription { get; set; }
public ICollection<SubCategory> SubCategories { get; set; }
}现在使用linq中的投影进行映射;
public List<CategoryViewModel> GetAllCategories()
{
using (var db =new Entities())
{
var categoriesList = db .Categories
.Select(c => new CategoryViewModel() // here is projection to your view model
{
CategoryId = c.CategoryId,
CategoryName = c.Name,
CategoryDescription = c.Description
});
return categoriesList.ToList<CategoryViewModel>();
};
}现在你的控制器;
ICategoryRepository _catRepo;
public CategoryController(ICategoryRepository catRepo)
{
//note that i have also used the dependancy injection. so i'm skiping that
_catRepo = catRepo;
}
public ActionResult Index()
{
//ViewBag.CategoriesList = _catRepo.GetAllCategories();
or
return View(_catRepo.GetAllCategories());
}最后是你的观点;
@model IEnumerable<CategoryViewModel>
@foreach (var item in Model)
{
<h1>@item.CategoryName</h1>
}https://stackoverflow.com/questions/15863201
复制相似问题