我有两个简单的类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>
这是db上下文类:
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.
我做错了什么?
答案 0 :(得分:5)
问题是Followers
集合为空。不要新建你的课程,而是让EF create为你...
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; }
}
答案 1 :(得分: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();
答案 2 :(得分:0)
试试这个。您必须更改快速
中提到的构造函数 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();
答案 3 :(得分:0)
您可以初始化List,因为ICollection是一个接口,因此无法初始化,但是List可以(以下对我有用)
代替:
task.Followers.Add(follower);
写:
task.Followers= new List<User>();
task.Followers.Add(follower);
这应该可以解决您的问题:)