我有两个简单的课程,User
并且Task
:
class User
{
public int UserId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
class Task
{
public int TaskId { get; set; }
public string Name { get; set; }
public DateTime CreatedAt { get; set; }
public virtual ICollection<User> Followers { get; set; }
}
Task 类有一个属性Followers
,它是ICollection<User>
这是数据库上下文类:
class MyContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Task> Tasks { get; set; }
protected override void OnModelCreating(DbModelBuilder mb)
{
mb.Entity<User>().HasKey(u => u.UserId);
mb.Entity<Task>().HasKey(t => t.TaskId);
}
}
这是主程序中的代码:
var db = new MyContext();
var user = new User();
user.Name = "John Doe";
user.Email = "jd@email.com";
db.Users.Add(user);
db.SaveChanges();
var follower = db.Users.Where(u => u.Name == "John Doe").FirstOrDefault();
var task = new Task();
task.Name = "Make the tea";
task.CreatedAt = DateTime.Now;
task.Followers.Add(follower); // ERROR
db.Tasks.Add(task);
db.SaveChanges();
问题是我在尝试将追随者添加到任务时遇到错误。
Object reference not set to an instance of an object.
我究竟做错了什么?