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 = "[email protected]";
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?
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With