3

我有两个简单的课程,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.

我究竟做错了什么?

4

4 回答 4

6

问题是该Followers集合为空。让 EF为您创建它们,而不是更新您的课程...

var user = db.Users.Create();

var task = db.Tasks.Create();

如果您仍然遇到问题,那么您的代理不会被创建。您可以在类构造函数中初始化集合,使它们中的每一个都成为HashSet<T>. 最好确定为什么没有生成代理......

public class Task
{
    public Task()
    {
       Followers = new HashSet<User>();
    }
    public int TaskId { get; set; }
    public string Name { get; set; }
    public DateTime CreatedAt { get; set; }
    public virtual ICollection<User> Followers { get; set; }
}
于 2013-06-07T10:02:07.460 回答
4

尝试这个。只是初始化Follower

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 =  new Collection<User>()
task.Followers.Add(follower);

db.Tasks.Add(task);

db.SaveChanges(); 
于 2013-06-07T11:55:48.773 回答
0

尝试这个。您将不得不更改 qujck 提到的构造函数

        var db = new MyContext();

        var user = new User();
        user.Name = "John Doe";
        user.Email = "jd@email.com";

        var task = new Task();
        task.Name = "Make the tea";
        task.CreatedAt = DateTime.Now;

        task.Followers.Add(user);
        db.Tasks.Add(task);
        db.SaveChanges();
于 2013-06-07T11:32:36.310 回答
0

您可以初始化 List,因为 ICollection 是一个接口,因此无法初始化,但 List 可以(以下对我有用)

代替:

task.Followers.Add(follower);

写:

task.Followers= new List<User>();
task.Followers.Add(follower);

这应该可以解决您的问题:)

于 2018-10-18T18:58:47.993 回答