Search code examples
c#linqmvvmentity-framework-6devexpress-wpf

How to convert LINQ query data to WPF/MVVM List


I have two entities:

 public class Transport
    {
        [Key]
        public int TransportID {get; set;}
        public string Model { get; set; }
        public string Brand { get; set; }
    }
    public class TransportOwner
    {
        [Key]
        public int TransportOwnerID {get; set;}
        public int OwnerID {get; set;}
        public int TransportID {get; set;}
        [ForeignKey("TransportID")]
        public virtual Transport Transport { get; set; }
    }

In ViewModel I created two lists from these two entities:

public List<Transport> TransportList 
public List<OwnerTransport> OwnerTransportList

And I need to construct third list for my WPF/MVVM form with data from these two lists: Structure I need is:

OwnerTransportID
OwnerID
TransportID
Model
Brand

What do I do next in my ViewModel.cs? Do I need to create new class?

public class OwnerTransportTransport
{
    [Key]
    public int OwnerTransportID {get; set;}
    public int TransportID {get; set;}
    public string OwnerID {get; set;}
    public string Model { get; set; }

    public string Brand { get; set; }
}

and then

List<OwnerTransport> OwnerTransportTransportList 

?? Could You help?

Data I get from linq query:

var ownerTransportList = OwnerTransport.Select(t => new
{
    t.OwnerTransportID,
    t.OwnerID,
    t.TransportID,
    ModelName = t.Transport.ModelName,
    BrandName = t.Transport.BrandName,
}).ToList();

So I have data, and don't know how to convert it to List<OwnerTransportTranspot>.


Solution

  • Well you can actually do this:

    List<OwnerTransportTransport> ListIWantToShow =
                            (from transport in dbContext.TransportOwner
                            select new OwnerTransportTransport()
                            {
                                ID = transport.ID,
                                TransportID = transport.TransportID,
                                BrandName = transport.Transport.BrandName,
                                ModelName = transport.Transport.ModelName
                            }).ToList();
    
    
    public class OwnerTransportTransport
    {
      public int OwnerTransportID { get; set; }
      public int TransportID { get; set; }
      public string Brand { get; set; }
      public string Model { get; set; }
    }