4

I have two simple classes, User and 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; }
}

The Task class has a property Followers which is an ICollection<User>

Here is the db context class:

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

and here is the code in the Main program:

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();

The trouble is I am getting an error when trying to add the follower to the task.

Object reference not set to an instance of an object.

What am I doing wrong?

Philip Wade
  • 348
  • 2
  • 3
  • 10

4 Answers4

7

The problem is that the Followers collection is null. Instead of newing up your classes, let EF create them for you ...

var user = db.Users.Create();

and

var task = db.Tasks.Create();

If you're still getting problems then your proxies are not being created. You can initialise the collections in the class constructors, make each of them a HashSet<T>. It would be better though to identify why the proxies are not getting generated ...

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; }
}
qujck
  • 14,388
  • 4
  • 45
  • 74
  • I changed them to Create but that doesn't seem to solve the problem - still getting the same error. – Philip Wade Jun 07 '13 at 10:12
  • Is it always a `HashSet` that EF wants or is it irrelevant what type of `ICollection` the collections are? – default Oct 22 '13 at 12:26
  • btw, for other users coming here and have to implement the workaround, the reason is perhaps described [here](http://stackoverflow.com/questions/4069563/why-is-my-entity-framework-code-first-proxy-collection-null-and-why-cant-i-set) – default Oct 22 '13 at 12:35
  • @Default I believe it's irrelevant. We use an in-house implementation of `ICollection` – qujck Oct 22 '13 at 12:52
4

try this. just initialize 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(); 
Atish Kumar Dipongkor
  • 10,220
  • 9
  • 49
  • 77
0

Try this. You will have to chan ge the constructor as mentioned by 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();
Kosala W
  • 2,133
  • 1
  • 15
  • 20
0

You can initialize the List, because ICollection is an interface then it can't be initialized, but List can be (the following worked for me)

Instead of:

task.Followers.Add(follower);

Write:

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

This should solve your problem :)

Vega
  • 27,856
  • 27
  • 95
  • 103
Ulyses
  • 101
  • 1
  • 10