I use entity framework core 2.0 and mapster as object mapper.
An user can create news in my scenario.
I have this method:
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();
}
which works as I want. But instead of writing my selected properties by hand, I want to use mapster. Therefore I have this class:
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; }
}
and tried something like this:
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();
}
But it doesn't work. My SQL-Profiler show me this:
SELECT applicationUser.UserName as author
FROM News
INNER JOIN Users ON News.AuthorId = Users.ID;
So it doesn't project the properties from NewsMasterDTO.
If I write it this way:
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();
}
the property selection works but the join to get the Username doesn't. SQL-Profiler shows something like this:
SELECT id, headline, image, text, date
FROM News
INNER JOIN Users ON News.AuthorId = Users.ID;
But as you can see, the author in the SELECT is missing...
Is there any way to achieve my goal, so that I can describe my selected properties in my NewsMasterDTO class instead of writing it in the resultSelector explicit?
Thank you in advance!