C#使用mapster映射IQueryable中的匿名对象

时间:2018-01-25 13:46:11

标签: c# entity-framework mapster

我使用实体框架核心2.0和mapster作为对象映射器。

用户可以在我的场景中创建新闻。

我有这个方法:

public List<NewsMasterDTO> GetMasterData()
{
      IQueryable<News> news = dbcontext.News;
      IQueryable<ApplicationUser> user = dbcontext.Users;
      return news.Join(inner: user, outerKeySelector: newsDB =>   newsDB.UserId,
          innerKeySelector: applicationUser => applicationUser.Id,
          resultSelector: (newsSelector, applicationUser) =>
                           new
                           {
                            newsSelector.ID,
                            newsSelector.Date,
                            newsSelector.Image,
                            newsSelector.Headline,
                            newsSelector.Text,
                            Author= applicationUser.UserName
                           }).ToList();
}

按我的意愿工作。但是我没有手动编写我选择的属性,而是想使用mapster。所以我有这个班:

  public class NewsMasterDTO
  {
    public int ID { get; set; }
    public string Headline{ get; set; }
    public byte[] Image{ get; set; }
    public string Text { get; set; }
    public DateTime Date{ get; set; }
    public string Author{ get; set; }
  }

尝试过这样的事情:

 public List<NewsMasterDTO> GetMasterData()
    {
          IQueryable<News> news = dbcontext.News;
          IQueryable<ApplicationUser> user = dbcontext.Users;
          return news.Join(inner: user, outerKeySelector: newsDB =>   newsDB.UserId,
              innerKeySelector: applicationUser => applicationUser.Id,
              resultSelector: (newsSelector, applicationUser) =>
                               new
                               {
                                newsSelector,
                                Author= applicationUser.UserName
                               })
                               .ProjectToType<NewsMasterDTO>()
                               .ToList();
    }

但它不起作用。我的SQL-Profiler告诉我这个:

SELECT applicationUser.UserName as author
FROM News
INNER JOIN Users ON News.AuthorId = Users.ID;

因此它不会从NewsMasterDTO投射属性。

如果我这样写:

 public List<NewsMasterDTO> GetMasterData()
    {
          IQueryable<News> news = dbcontext.News;
          IQueryable<ApplicationUser> user = dbcontext.Users;
          return news.Join(inner: user, outerKeySelector: newsDB =>   newsDB.UserId,
              innerKeySelector: applicationUser => applicationUser.Id,
              resultSelector: (newsSelector, applicationUser) => newsSelector)

                               .ProjectToType<NewsMasterDTO>()
                               .ToList();
    }

属性选择有效,但是获取用户名的连接不起作用。 SQL-Profiler显示如下内容:

SELECT id, headline, image, text, date
FROM News
INNER JOIN Users ON News.AuthorId = Users.ID;

但正如您所看到的,SELECT中的作者遗失了......

有没有办法实现我的目标,以便我可以在NewsMasterDTO类中描述我选择的属性,而不是在resultSelector中显式写入?

提前谢谢!

0 个答案:

没有答案