2016-04-02 189 views
0

我有文章和作者類。實體模型映射LINQ

取物品,像這樣和地圖實體模型:

public List<Model.Article> GetArticleList() { 
    using (var db = new ArticlesContext()) { 
     return db.Articles.Select(t => new Model.Article() { 
      Author = MapUserEntityToModel(db.Users.FirstOrDefault(u => u.UserID == t.UserID)) 
      Title = t.Title, 
      Teaser = t.Teaser 
      // etc 
     }).ToList(); 
    } 
} 

這不起作用,因爲LINQ不能運行在運行時該功能。什麼是最簡單和最乾淨的方法來做映射?

這裏是模型:

namespace Model { 
    public class Article { 
     public string Title { get; set; } 
     public string Teaser { get; set; } 
     public User Author { get; set; } 
     public DateTime DateAdded { get; set; } 
    } 

    public class User { 
     public string DisplayName { get; set; } 
     public string Email { get; set; } 
     public string Website { get; set; } 
     public string PasswordHash { get; set; } 
    } 
} 

這裏有實體:

namespace MyProj { 
    public class Article { 
     [Key] 
     public int ArticleID { get; set; } 
     public string Title { get; set; } 
     public string Teaser { get; set; } 
     public int UserID { get; set; } 
     public DateTime DateAdded { get; set; } 
    } 

    public class User { 
     [Key] 
     public int UserID { get; set; } 
     public string DisplayName { get; set; } 
     public string Email { get; set; } 
     public string Website { get; set; } 
     public string PasswordHash { get; set; } 
    } 

    public class ArticleContext : DbContext { 
     public ArticleContext() : base("name=conn") { 
      public DbSet<Article> Articles { get; set; } 
      public DbSet<User> Users { get; set; } 
     } 
    } 
} 

回答

0

之前繼續,映射你的導航屬性的關係:

public class Article { 
    [Key] 
    public int ArticleID { get; set; } 
    public string Title { get; set; } 
    public string Teaser { get; set; } 

    [ForeignKey("UserID")] 
    public virtual User Author {get; set; } // navigation property 

    public int UserID { get; set; } 
    public DateTime DateAdded { get; set; } 
} 

然後就是項目的導航屬性,以他的等效模型:

public List<Model.Article> GetArticleList() { 
    using (var db = new ArticlesContext()) { 
     return db.Articles.Select(t => new Model.Article() { 
      Author = new Model.User { 
       DisplayName = t.User.DisplayName, 
       Email = t.User.Email, 
       Website = t.User.Website, 
       PasswordHash = t.User.PasswordHash 
      }, 
      Title = t.Title, 
      Teaser = t.Teaser 
      // etc 
     }).ToList(); 
    } 
} 
0

你不需要做任何事情,只是返回db.Articles直接:

using Model; 

public List<Article> GetArticleList() { 

    using(var db = new ArticlesContext()) { 
     return db.Articles.ToList(); 
    } 
} 

假設你的EF模型使用外鍵正確設置,您的Article類型將進行懶惰評估Author屬性在訪問時將返回User對象。