我对 .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/