开发者

Trouble debugging asp.net mvc3 blog application : Sequence contains no elements

开发者 https://www.devze.com 2023-03-18 11:54 出处:网络
i m currently working on a tutorial for a blog using ado.net and mvc3 (in c#). I m fairly new to developing so please cut me some slack! Anyways I m having trouble debugging one of the data controller

i m currently working on a tutorial for a blog using ado.net and mvc3 (in c#). I m fairly new to developing so please cut me some slack! Anyways I m having trouble debugging one of the data controllers responsible for reading (validation is turned off) user posts and adding them to the blog. The code breaks down at the GetPost function (marked with a comment). Any help would be greatly appreciated

` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Blog.Models; using 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 ?? st开发者_开发问答ring.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 is where I get the exception '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; } }
    }
}

` EDIT 16:29 GMT Yep you guys are right on the money! That went trough nicelly, thanks! Whats weird is I m now getting Nullreference exception on this bit

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

do I have to declare them somehow or am i missing something else?

Nevermind the edit above, that was just a typo. Thanks again


Try using FirstOrDefault(). If a LINQ expression yield no result, it is likely that with the methods First() or Single() you'll end up with the 'Sequence contains no elements' expection.

Edit: When using FirstOrDefault(), the Default means null. You need to check if GetPost returns null.


My guess is that model.Posts does not contain any elements and thus trying to perform a First() will cause the error you're getting.

Using FirstOrDefault() instead will return the default value of the type should no items be found in the collection.


Your problem is most likely that the results of the model.Posts.Where(x => x.ID == id) query are empty, which makes the First() method throw your error, which is the default behavior when querying the first element of an empty result set.

Try using FirstOrDefalut instead of First, which will returns null intead of throwing an exception. And of course, test if your result is null aftewards so you don't try using empty objects !

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号