2013-04-07 167 views
1

我是MVC和EF的新手。遵循一些好的教程,我最終創建了我的POCO類。將POCO類映射到MVC模型

我想創建一個MVC模型與分層體系結構中的POCO類的幫助。我的POCO課程位於類庫項目Entities中。

而我的MVC4應用程序是Web項目,它引用實體。

我查詢數據庫,並在實體中有內容,並希望映射3-4個POCO類到單個模型,所以我可以創建一個強類型的視圖。

我不確定如何繼續。幫我解決這個問題。

回答

2

查看ASP.NET MVC in Action book.。它有一整章致力於這個話題。他們建議並展示如何使用AutoMapper將域實體映射到ViewModels。我也有一個例子here

在引導程序:

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);    
     }  
+0

謝謝@derek。有沒有在線鏈接快速檢查out.Ordering可能需要時間,我會做。 – user2067567 2013-04-07 14:10:43

+0

https://github.com/jeffreypalermo/mvc2inaction/tree/master/src查看第2和3章的來源 – 2013-04-07 14:13:46

+0

和https://bitbucket.org/dbeattie/feedtracker – 2013-04-07 14:21:34

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> 
}