麻烦调试asp.net mvc3博客应用程序:序列不包含任何元素

时间:2011-07-07 13:41:29

标签: c# asp.net asp.net-mvc-3 ado.net

我目前正在使用ado.net和mvc3(在c#中)编写博客教程。我是一个相当新的开发人员,所以请给我一些懈怠!无论如何,我在调试一个负责阅读(验证已关闭)用户帖子并将其添加到博客的数据控制器时遇到问题。代码在GetPost函数中分解(标记为注释)。 任何帮助将不胜感激

`使用System;     使用System.Collections.Generic;     使用System.Linq;     使用System.Web;     使用System.Web.Mvc;     使用Blog.Models;     使用System.Text;

namespace Blog.Controllers
{
    public class PostsController : Controller
    {
        private BlogModel model = new BlogModel();

        public ActionResult Index()
        {
            return View();
        }
        [ValidateInput(false)]
        public ActionResult Update(int? id, string title, string body, DateTime dateTime, string tags)
        {
            if (!IsAdmin)
            {
                return RedirectToAction("Index");
            }

            Post post = GetPost(id);
            post.Title = title;
            post.DateTime = dateTime;
            post.Body = body;
            post.Tags.Clear();

            tags = tags ?? string.Empty;
            string[] tagNames = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string tagName in tagNames)
            {
                post.Tags.Add(GetTag(tagName));

            }

            if (id.HasValue)
            {
                model.AddToPosts(post);
            }
            model.SaveChanges();
            return RedirectToAction("Details", new { id = post.ID });
        }

        public ActionResult Edit(int? id)
        {
            Post post = GetPost(id);
            StringBuilder tagList = new StringBuilder();
            foreach (Tag tag in post.Tags)
            {
                tagList.AppendFormat("{0} ", tag.Name);
            }
            ViewBag.Tags = tagList.ToString();
            return View(post);
        }

        private Tag GetTag(string tagName)
        {
            return model.Tags.Where(x => x.Name == tagName).FirstOrDefault() ?? new Tag() { Name = tagName };
        }

/ * Bellow是我得到异常'Sequence contains no elements'* /

的地方
        private Post GetPost(int? id)
        {
            return id.HasValue ? model.Posts.Where(x => x.ID == id).First() : new Post() { ID = -1 };
        }

        public bool IsAdmin { get { return true; } }
    }
}

` 编辑16:29 GMT 你们这些钱是对的!那已经过去了,谢谢! 奇怪的是我现在在这个位上得到Nullreference异常

            post.Title = title;
            post.DateTime = dateTime;
            post.Body = body;

我必须以某种方式声明它们或者我错过了其他的东西吗?

没关系上面的编辑,这只是一个错字。再次感谢

3 个答案:

答案 0 :(得分:1)

尝试使用FirstOrDefault()。如果LINQ表达式没有产生任何结果,那么很可能使用方法First()Single(),您将最终得到'序列不包含元素'的预期。

修改:使用FirstOrDefault()时,Default表示null。您需要检查GetPost是否返回null

答案 1 :(得分:0)

我的猜测是model.Posts不包含任何元素,因此尝试执行First()会导致您收到的错误。

如果在集合中找不到任何项目,则使用FirstOrDefault()将返回该类型的默认值。

答案 2 :(得分:0)

您的问题很可能是model.Posts.Where(x => x.ID == id)查询的结果为空,这使得First()方法抛出您的错误,这是查询空结果集的第一个元素时的默认行为

尝试使用FirstOrDefalut代替First,这将返回引发异常的null内容。当然,测试一下你的结果是否为null,这样你就不会尝试使用空对象了!