c# - "Member access ' DataType MemberName ' of ' Namespace.ClassName ' not legal on type ' System.Collections.Generic.IEnumerable `1[Namespace.ClassName]."

标签 c# linq-to-sql

我很想找到解决我当前问题的方法,但如果我能理解该错误的实际含义,我会更喜欢。

我的数据库中有两个表的 LINQ to SQL 类:ProvidersAssignments。我将以下成员添加到 Provider 类:

public IEnumerable<Assignment> Assignments 
    {
        get
        {
            return (new linqDataContext())
                .Assignments
                .Where(a => a.ProviderID == this.ProviderID);
        }
    }

然后,我使用从父 Provider 提取并使用子成员 Assignments 的查询绑定(bind) GridView,如下所示:

protected void PopulateProviders()
    {
        linqDataContext context = new linqDataContext();
        var list = from p in context.Providers
                   where (p.Assignments.Count(a => a.Category == ddlCategory.SelectedValue) > 0)
                   select p;

        lvProviders.DataSource = list;
        lvProviders.DataBind();
    }

在 .DataBind() 中,当它实际运行查询时,会抛出以下错误:

Member access 'System.String Category' of 'Namespace.Assignment' not legal on type 'System.Collections.Generic.IEnumerable`1[Namespace.Assignment].

我试过检查空值 (a => a != null && a.Category ...) 但没有成功。我不确定接下来要尝试什么。我认为,如果我知道错误试图告诉我什么,我就能找到解决方案。就目前而言,我不知道为什么成员访问是非法的。

最佳答案

Assignments 属性完全错误。首先,属性 getter 不应该有副作用,更重要的是,实体类不应该对 DataContext 有反向依赖。 Linq to SQL 无法破译此查询;它依赖于执行 Linq to SQL 无法理解的各种疯狂操作的属性。

现在摆脱Assignments属性。而不是这样做,您需要将此查询编写为连接:

int category = (int)ddlCategory.SelectedValue;
var providers =
    from p in context.Providers
    join a in context.Assignments
        on p.ProviderID equals a.ProviderID
        into g
    where g.Count(ga => ga.Category == category) > 0
    select p;

如果我正确理解了您的代码的意图,那应该可以完成您想要做的事情。

最后一点注意:您永远不会在任何方法中正确处理 DataContext。你应该像这样包装它:

using (var context = new linqDataContext())
{
    // Get the data here
}

关于c# - "Member access ' DataType MemberName ' of ' Namespace.ClassName ' not legal on type ' System.Collections.Generic.IEnumerable `1[Namespace.ClassName].",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2284492/

相关文章:

c# - Entity Framework Core 从现有数据库创建模型

multithreading - System.Linq.Dynamic .Select ("new ...") 似乎不是线程安全的

C# 编译器错误?为什么这个隐式的用户定义转换不能编译?

字符串格式的 C# 秒到 TimeSpan

c# - LINQ - .Cast<T>() 选择记录吗?

linq-to-sql - 在LINQ to SQL下管理不同开发人员的连接字符串

c# - 使用 Linq To Sql 从 DataGridView 获取选定行后面的实体

linq-to-sql - 域中定义的规范模式

c# - session 可以在 session 结束时间调用 dispose 方法吗?

c# - 由于缺乏权限而无法访问引用?