关于我的上下文,无法访问已处置的对象

时间:2019-06-15 20:42:38

标签: c# .net linq

我不确定为什么会出现此错误。

 public IEnumerable<object> Search(string query)
    {

        using (var context = new MessageContext())
        {
            string[] words = query.Split(" ");
            var messages = (from m in context.Messages
                          join u in context.Users on m.UserId equals u.UserID
                          select new
                          {
                              m.Id,
                              m.Date,
                              m.Name,
                              m.Text,
                              m.UserId,
                              u.Image
                          });

            foreach (string word in words)
            {
                messages = messages.Where(u => u.Name.Contains(word)).Union(messages.Where(u => u.Text.Contains(word)));
            }

            return messages;
        }
    }

而且我不断收到错误消息

System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'MessageContext'.

最终,我想我希望将最后一行设为return messages.tolist(),但是当我这样做时,我得到了错误-

'IQueryable<<anonymous type: int Id, string Date, string Name, string Text, string UserId, string Image>>' does not contain a definition for 'toList' and no accessible extension method 'toList' accepting a first argument of type 'IQueryable<<anonymous type: int Id, string Date, string Name, string Text, string UserId, string Image>>' could be found (are you missing a using directive or an assembly reference?)

这里是C#的新手,完全卡住了。有什么建议吗?

0 个答案:

没有答案