【问题标题】:LINQ To Return Properties from a classLINQ 从类返回属性
【发布时间】:2020-07-20 13:37:54
【问题描述】:

首先,XAML 和一般编程的新手。我正在尝试在 .cs 文件中填充 XAML 数据网格。

我使用的每个 SQL 表都有类,包含引用列的属性

    public partial class TTDepartment
    {
        public TTDepartment()
        {
            this.TTEventLogs = new HashSet<TTEventLog>();
            this.TTUserDepartments = new HashSet<TTUserDepartment>();
        }

        public string Department { get; set; }
        public string Manager { get; set; }
        public string ManagerEmail { get; set; }

        public virtual ICollection<TTEventLog> TTEventLogs { get; set; }
        public virtual ICollection<TTUserDepartment> TTUserDepartments { get; set; }
    }

我目前正在做的是尝试在我的类上使用 LINQ 查询来检索数据,就像这样

(我知道可能有更好的方法来做到这一点)请帮助

        private void GetDepartments()
        {

            using (var context = new CetusEntities())// New instance of Database class
            {
                var linqDept = context.TTDepartments.Where(s => s.Department != "" || s.Department != null); // Should return All Departments from TTDepartments Class?
                //Populate colDept in Datagrid with results from LINQ
            } 
        }

这是 Datagrid 的 XAML

                <DataGrid x:Name="dgDept"  Height="200">
                    <DataGrid.Columns>
                        <DataGridTextColumn x:Name="colDept" Binding="{Binding Source = {StaticResource Department}}" Header="Department"></DataGridTextColumn>
                        <DataGridTextColumn x:Name="colMan" Binding="{Binding Source = {StaticResource Department}}" Header="Manager"></DataGridTextColumn>
                        <!--<DataGridTextColumn Header="Email"></DataGridTextColumn>-->
                    </DataGrid.Columns>
                </DataGrid>

【问题讨论】:

  • 这不起作用还是什么?更好的方法是什么意思?
  • var linqDept 没有返回我想要访问的属性
  • 请看我的回答。
  • 我测试了你的 LINQ 查询,发现它仍然返回为空或 null 的部门,你有同样的问题吗?如果你用var linqDept = TTDepartments.Where(x =&gt; !string.IsNullOrEmpty(x.Department));这个方法来排除Department属性为空或者null值的,能行吗?

标签: c# wpf linq xaml uwp-xaml


【解决方案1】:

您的查询应如下所示:

var linqDept = context.TTDepartments.Where(s =>(!string.IsNullOrEmpty(s)));

另外,请确认您的数据库中确实有数据。然后调试

//设置要测试的数据网格源。

dtGrid.ItemsSource = linqDept;

XAML 示例:

<DataGridTextColumn x:Name="colDept" Binding="{Binding Department}" Header="Department"></DataGridTextColumn>

【讨论】:

  • 好的,需要改写,问题不是最好的。结果是否为空都没有关系,我只想从我的 SQL 表中返回整个列 Departments(没有空值)...... != 只是我用来实现这一目标的逻辑。因此,我说必须有更好的方法来使用 LINQ 访问 TTDepartment.Department。感谢您的宝贵时间
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 1970-01-01
  • 2013-05-10
  • 2017-06-06
相关资源
最近更新 更多