LINQ中的模型映射实体

时间:2016-04-02 23:04:19

标签: c# entity-framework 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; }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

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

using Model;

public List<Article> GetArticleList() {

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

假设您的EF模型使用外键正确设置,您的Article类型将具有延迟评估的Author属性,该属性将在访问时返回User个对象。

答案 1 :(得分: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();
    }
}