c# - ASP.NET MVC3 - "Object reference not set to an instance of an object"错误

标签 c# asp.net asp.net-mvc-3 ef-code-first

我对 .NET 和 MVC3 比较陌生。尝试添加对象的实例时,我遇到了上述错误消息的问题。下面是我的代码:

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; }
}

我在下面发布的 Controller 中收到错误

    [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");
    }

我已经在谷歌上搜索了很长时间,并且一直在关注 ScottGu 的“代码优先与现有数据库”示例,其中的代码非常相似,但我没有运气。任何帮助表示赞赏。谢谢。

最佳答案

您的关联列表需要在向其添加项目之前实例化。

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

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

关于c# - ASP.NET MVC3 - "Object reference not set to an instance of an object"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8740877/

相关文章:

asp.net-mvc-3 - Autofac 相当于 Ninject 的 WhenInjectedInto()

asp.net-mvc-3 - 当我按照此示例操作时,为什么会出现解析器错误?

C# 'Index was outside the bounds of the array.' 用于一个数组而不是另一个

c# - 从 MVC4 中的表单获取数据

c# - 如何访问 ThisAddIn 类之外的 VSTO Outlook 加载项中的应用程序属性?

ASP.NET 图像大小调整和裁剪

javascript - 如何启用asp :LinkButton on client side

c# - 我的自定义模型绑定(bind)程序的 AttemptedValue 包含键和值

C# - 多个 if else 语句无法正常工作

asp.net-mvc - 为每个用户生成不同的 AntiForgeryToken 的方法是什么