Home C# Entity Framework, Simplify Select Child Property That Using Same Condition
Reply: 1

C# Entity Framework, Simplify Select Child Property That Using Same Condition

user1734423
1#
user1734423 Published in 2017-12-07 15:02:57Z

I have 2 ef model, let's say Task() and Progress()

public class Task()
{
    public int Id { get; set; }
    public string Title { get; set; }
}

and then

public class Progress()
{
    public int Id { get; set; }
    public int Id_Task { get; set; }
    public string Status { get; set; }
    public DateTime Update { get; set; }
}

I want to get data for each task and it's last progress, So i make a ViewModel

public class ViewTask()
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Last_Status { get; set; }
    public DateTime Last_Update { get; set; }
}

Right now, this is what i did:

var data = _context.Task
    .Select(x => new ViewTask
    {
        Id = x.Id,
        Title = x.Title,
        Last_Status = x.Progress.OrderByDescending(y => y.Update)
            .Select(y => y.Status).FirstOrDefault(),
        Last_Update = x.Progress.OrderByDescending(y => y.Update)
            .Select(y => y.Update).FirstOrDefault()
    }).ToList();

Is there any better ways so I don't need to repeat x.Progress... part? The only code i can think of is something like this:

var data = _context.Task
    .Select(x => new
    {
        Id = x.Id,
        Title = x.Title,
        Progress = x.Progress.OrderByDescending(y => y.Update).FirstOrDefault()
    })
    .Select(x => new ViewTask
    {
        Id = x.Id,
        Title = x.Title,
        Last_Status = x.Progress.Status
        Last_Update = x.Progress.Update
    }).ToList();

I appriciete any kind of suggestion. Thanks :)

Jayakrishnan Gounder
2#
Jayakrishnan Gounder Reply to 2017-12-07 16:08:50Z

You can use MaxBy and MinBy methods from moreLINQ library.

var data = _context.Task
.Select(x => new ViewTask
{
    Id = x.Id,
    Title = x.Title,
    Last_Status = x.Progress.MaxBy(y => y.Update).Status,
    Last_Update = x.Progress.MaxBy(y => y.Update).Update
 }).ToList();

Hope it helps!!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.334358 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO