如何初始化我的模型

时间:2014-01-10 12:19:32

标签: c# asp.net-mvc c#-4.0 icollection

首先,我想告诉你我的模特。

public class Blog
{
    [Key]
    public int BlogID { get; set; }
    public System.Nullable <DateTime> LastModified { get; set; }
    public System.Nullable<int> AidID { get; set; }
    public virtual BlogAid BlogAid{ get; set; }
    public System.Nullable<int> AuthorID { get; set; }
    public virtual BlogAuthor BlogAuthor { get; set; }
    public System.Nullable<int> CommentID { get; set; }
    public virtual ICollection<BlogComment> BlogComment { get; set; }
    public System.Nullable<int> TitleID { get; set; }
    public virtual BlogTitle BlogTitle { get; set; }
    public System.Nullable<int> ContentID { get; set; }
    public virtual BlogContent BlogContent { get; set; }
    public System.Nullable<int> NewsID { get; set; }
    public virtual BlogNews BlogNews { get; set; }
}

特别是对于这一行:

public virtual ICollection<BlogComment> BlogComment { get; set; }

这意味着我在博客和评论之间有一对多的关系,然后看到我的控制器:

var comments = from c in DB.BlogCommenttbl
                      join b in DB.Blogtbl on c.BlogID equals b.BlogID
                      where c.CommentID > 0
                      select new
                      { Comments = c.Comments, LastModified=c.LastModifed};

if (comments.FirstOrDefault() !=null)
{
    bpm.Blogs.BlogComment = new List<BlogComment>();

    foreach (var item in comments.ToList())
    {
        bpm.Blogs.BlogComment.Add(new BlogComment{Comments=item.Comments, LastModifed=item.LastModified});
    }
}

并且视图是

@foreach (var item in Model.Blogs.BlogComment)
{
    <h3>Start Bootstrap <small>@Html.DisplayText(item.LastModifed.ToString())</small></h3>
    <p>@Html.DisplayText(item.Comments.ToString())</p>
}

但我收到Object reference not set to an instance of an object.错误。

然后我调试了代码并找到了

bpm.Blogs.BlogComment = new List<BlogComment>();

无法正常工作,我该如何修复此错误?或者处理这个问题?

2 个答案:

答案 0 :(得分:3)

可能您没有初始化bpm.Blogs属性。在行bpm.Blogs.BlogComment = new List<BlogComment>();之前,您必须初始化Blogs

bpm.Blogs = new Blog();

答案 1 :(得分:0)

if (comments.FirstOrDefault() !=null)
{
    bpm.Blogs.BlogComment = new List<BlogComment>();

    foreach (var item in comments.ToList())
    {
        bpm.Blogs.BlogComment.Add(new BlogComment{Comments=item.Comments, LastModifed=item.LastModified});
    }
}

如果 comments 不包含任何项目,则代码块将不会被执行。如果未执行,则不会实例化bpm.Blogs.BlogComment。将其更改为:

bpm.Blogs.BlogComment = new List<BlogComment>();

if (comments.FirstOrDefault() !=null)
{
    foreach (var item in comments.ToList())
    {
        bpm.Blogs.BlogComment.Add(new BlogComment{Comments=item.Comments, LastModifed=item.LastModified});
    }
}