ASP.NET MVC3-“对象引用未设置为对象的实例"错误 [英] ASP.NET MVC3 - "Object reference not set to an instance of an object" error

查看:52
本文介绍了ASP.NET MVC3-“对象引用未设置为对象的实例"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对.NET和MVC3比较陌生.尝试添加对象的实例时,上述错误消息出现了一些麻烦.下面是我的代码:

I'm relatively new to .NET and MVC3. I'm having some trouble with the above error message when trying to add an instance of an object. Below is my code:

KeyDate类

public class KeyDate
{
    [Key]
    public int KeyID { get; set; }

    [StringLength(1000), Required]
    public string Title { get; set; }

    [Required]
    public string Description { get; set; }

    [Required]
    [Display(Name = "Event Date")]
    public DateTime EventDate { get; set; }

    [Display(Name = "Event End Date")]
    public DateTime? EventEndDate { get; set; }

    [Display(Name = "Course ID")]
    public int? CourseID { get; set; }

    [Display(Name = "Event ID")]
    public int? EventID { get; set; }

    public DateTime Created { get; set; }

    [Display(Name = "Created By")]
    public string CreatedBy { get; set; }

    public DateTime? Deleted { get; set; }

    [Display(Name = "Deleted By")]
    public string DeletedBy { get; set; }

    public virtual ICollection<Association> Associations { get; set; }
}

协会班

public class Association
{
    [Key, ForeignKey("KeyDate")]
    [Column(Order = 1)]
    public int KeyID { get; set; }

    [Key, ForeignKey("Category")]
    [Column(Order = 2)]
    public int CategoryID { get; set; }

    public virtual KeyDate KeyDate { get; set; }
    public virtual Category Category { get; set; }
}

我在下面的我的控制器"中收到错误消息

I am getting the error in my Controller posted below

    [HttpPost]
    public ActionResult Create(KeyDate keyDate, int topic)
    {
        keyDate.Created = DateTime.Now;
        keyDate.CreatedBy = User.Identity.Name;

        // Create topic association
        Association keyDateTopic = new Association();
        keyDateTopic.CategoryID = topic;
        keyDate.Associations.Add(keyDateTopic); // <-- Object reference... error here

        repository.Add(keyDate);
        repository.Save();

        return RedirectToAction("Index");
    }

我已经用Google搜索了很长时间,并且一直遵循ScottGu的现有数据库中的代码优先"示例,该示例中的代码非常相似,但是我没有运气.任何帮助表示赞赏.谢谢.

I have Googled this for ages, and have been following ScottGu's "Code First with Existing Database" example in which the code is quite similar, but I have had no luck. Any help appreciated. Thanks.

推荐答案

在添加项目之前,必须先实例化您的关联"列表.

Your Assosiactions List needs to be instantiated before adding items to it.

最佳做法是在构造函数中执行此操作.

Best practice is to do this from within the constructor.

public class KeyDate
{
...
    public virtual ICollection<Association> Associations { get; set; }
    public KeyDate()
    {
       Associations = new List<Association>()
    }
}

这篇关于ASP.NET MVC3-“对象引用未设置为对象的实例"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆