简体   繁体   English

如何将LINQ to SQL查询结果添加到Observable Collection?

[英]How to add LINQ to SQL query results to Observable Collection?

In WPF app I have an Observable Collection which is connected through databinding with ListView. 在WPF应用程序中,我有一个Observable Collection,它通过数据绑定与ListView连接。 I would like to populate this Observable Collection from LINQ to SQL query, but with no success. 我想将这个Observable Collection从LINQ填充到SQL查询,但没有成功。 In fact my code even doesn't compile (I pointed out the problem lines with comments). 实际上我的代码甚至没有编译(我指出了带注释的问题行)。

The structure of underlying Observable Collection Class is similar to the structure of SQL table from which I try to get a query. 底层Observable Collection Class的结构类似于我试图获取查询的SQL表的结构。

Please, what's wrong with my approach? 请问,我的做法有什么问题?

Here is part of my code: 这是我的代码的一部分:

ObservableCollection<ShowsQu> _ShowQuCollection =
            new ObservableCollection<ShowsQu>();

    public ObservableCollection<ShowsQu> ShowQuCollection
    { get { return _ShowQuCollection; } }

    public class ShowsQu
    {
        public string ShowCode { get; set; }
        public DateTime Date { get; set; }
        public TimeSpan Time { get; set; }
        public string Description { get; set; }
    }

    private void VisualizeAllShows()
    {

        MyfirstdbDataContext context = new MyfirstdbDataContext();
        _ShowQuCollection.Clear();

        var sh = from p in context.Shows select p;

        foreach (var p in sh)  
          _ShowCollection.Add(new ShowsQu
            {
                Date = sh.Date, //here is compile-time error
                Time = sh.Time, //here is compile-time error
                Description = sh.Description //here is compile-time error
            });
        }          
    }

Subst sh / p ( sh is the query, p is the current iterator item): Subst sh / psh是查询, p是当前迭代项):

foreach (var p in sh)  {
    _ShowCollection.Add(new ShowsQu {
        Date = p.Date,
        Time = p.Time,
        Description = p.Description
    });
}

BTW, you could just use foreach(var p in context.Shows) {...} here. 顺便说一句,你可以在这里使用foreach(var p in context.Shows) {...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM