我是MVC和EF的新手。在一些Nice Tutorials之后,我终于创建了我的POCO类。
我正在尝试在分层架构中借助POCO类创建MVC模型。我的POCO类位于名为Entities
的类库项目中。
我的MVC4应用程序是一个引用实体的Web
项目。
我查询数据库并在实体中包含内容,并希望将3-4个POCO类映射到单个模型,以便创建强类型视图。
我不确定如何继续。帮我这个。
答案 0 :(得分:2)
查看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);
}
答案 1 :(得分:2)
我之前曾经回答过这类问题,如果你想看到它,这里就是链接
http://stackoverflow.com/questions/15432246/creating-a-mvc-viewmodels-for-my-data/15436044#15436044
但如果您需要更多帮助,请通知我:D 这是你的viewmodel
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>
}