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

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

问题描述

我是比较新的.NET和MVC3。我遇到一些麻烦尝试添加对象的实例时,上面的错误消息。下面是我的code:

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搜索了好久了,并且已经先用现有的数据库code为例,其中code颇为相似以下ScottGu的,但我有没有运气。任何帮助AP preciated。谢谢你。

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.

推荐答案

您Assosiactions列表需要将项目添加到它之前被实例化。

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 - &QUOT;未将对象引用设置到对象&QUOT的实例;错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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