从LINQ查询结果构建WPF列表

时间:2016-06-15 06:52:56

标签: c# wpf linq entity-framework-6 devexpress

我需要学习如何从查询结果构建List

我的DBContext:

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 TransportID {get; set;}
    [ForeignKey("TransportID")]
    public virtual Transport Transport { get; set; }
}

public virtual DbSet<Transport> Transports { get; set; }
public virtual DbSet<TransportOwner> TransportOwners { get; set; }

在c#中我创建了List:

private List<OwnerTransport> _ownerTransportList;

还有来自我的DBContext的数据:

var ownerTransport = DBContext.OwnerTransports.AsQueryable();

var queryResult = ownerTransport
        .Select(t => new
        {
            t.ID,
            t.PersonalCode,
            t.TransportID,
            Model = t.Transport.Model,
            Brand = t.Transport.Brand, 
        }).ToList();

queryResult我想在OwnersTransportList中看到ant set是我的DataGrid的ItemSource

1 个答案:

答案 0 :(得分:0)

在通过EF将数据提取到内存之前,请考虑使用LINQ-to-Entities对(DB)存储中的数据执行过滤。

例如,要填充WPF GridControl,请执行以下代码。作为可能的过滤器的示例,我包含了一个where子句来过滤特定的TransportID

public ICollection<OwnerTransport> GetOwnerTransportByTransportId(int transportId, int? skip = null, int? take = null)
{
    using (var context = new DBContext())
    {
       // base query
       var query = context.OwnerTranports.AsQueryable();

       // execute filter on transport ID
       query = query.Where(t => t.TransportID == transportId.Value);

       // apply skip/take
       if (skip.HasValue)
       {
           query = query.Skip(skip.Value);
       }
       if (take.HasValue)
       {
           query = query.Take(take.Value);
       }         

       // Materialize data. This pulls it from DB store into memory.
       var data = query.ToList();

       return data;
    }
}