【问题标题】:Returning distinct data for a dropdownlist box with selectlistItem使用 selectlistItem 为下拉列表框返回不同的数据
【发布时间】:2016-11-07 17:36:06
【问题描述】:

我的数据库中有一个字段重复。我想在一个下拉列表中使用它,它必须返回不同的数据。

这是我为此创建的方法:

public IEnumerable<SelectListItem> GetBranches(string username)
{
    using (var objData = new BranchEntities())
    {
        IEnumerable<SelectListItem> objdataresult = objData.ABC_USER.Select(c => new SelectListItem
        {
            Value = c.BRANCH_CODE.ToString(),
            Text  = c.BRANCH_CODE
        }).Distinct(new Reuseablecomp.SelectListItemComparer());

        return objdataresult;
    }
    
}

这是我正在使用的课程:

public static class Reuseablecomp
{
    public class SelectListItemComparer : IEqualityComparer<SelectListItem>
    {
        public bool Equals(SelectListItem x, SelectListItem y)
        {
            return x.Text == y.Text && x.Value == y.Value;
        }

        public int GetHashCode(SelectListItem item)
        {
            int hashText  = item.Text  == null ? 0 : item.Text.GetHashCode();
            int hashValue = item.Value == null ? 0 : item.Value.GetHashCode();
            return hashText ^ hashValue;
        }
    }
}

没有返回任何内容,我收到以下错误。当我尝试没有Distinct 的基本查询时,一切正常。

{"The operation cannot be completed because the DbContext has been disposed."}  
System.Exception {System.InvalidOperationException}
Inner exception = null

如何为我的下拉菜单返回不同的数据?

【问题讨论】:

    标签: asp.net-mvc-4 linq-to-sql linq-to-entities


    【解决方案1】:

    从技术上讲,您的问题可以通过在您的 Distinct(...) 呼叫后附加 .ToList() 来解决。问题是查询是 JIT 评估的(及时)。换句话说,在需要查询所代表的实际数据之前,查询实际上并没有发送到数据库。调用ToList 就是这样一种需要实际数据的事情,因此会导致立即评估查询。

    但是,问题的根本原因是您在 using 语句中执行此操作。当方法退出时,查询还没有被评估,但你现在已经处理了你的上下文。因此,当需要实际评估该查询时,没有上下文可以执行它并且您会得到该异常。您真的应该永远将数据库上下文与using 结合使用。这只是灾难的秘诀。理想情况下,您的上下文应该是请求范围的,并且您应该使用依赖注入将其提供给需要它的任何对象或方法。

    此外,您只需将您的Distinct 呼叫移至您的Select 之前,您将不再需要自定义IEqualityComparer。例如:

    var objdataresult = objData.ABC_USER.Distinct().Select(c => new SelectListItem
    {
        Value = c.BRANCH_CODE.ToString(),
        Text = c.BRANCH_CODE
    });
    

    这里的操作顺序很重要。调用 Distinct 首先将其作为对数据库的查询的一部分包含在内,但之后调用它,就像你正在做的那样,在内存中的集合上运行它,一旦评估。然后,后者需要自定义逻辑来确定 IEnumerable&lt;SelectListItem&gt; 中不同项目的构成,这对于数据库查询版本显然不是必需的。

    【讨论】:

    • 谢谢。我需要比较用户名,如用户名 ==“ndjgkd”。在你的代码中我应该在哪里包含它?
    • 我不明白。 “喜欢”与“等于”(==)非常不同。它是哪一个?而且,比较如何?你想要发生什么?
    • 对不起,我的意思是等于。那是一个错字
    • 类似这样 Where(s => s.USERNAME == username)
    • Select 之前的任何位置。同样,这是一个操作顺序。在Select 之前是查询的一部分;在Select 之后,内存中的集合被过滤掉了。
    猜你喜欢
    • 2018-11-04
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    相关资源
    最近更新 更多