I have a strange issue with model connection. I'm using ASP.NET Core with SQL Server and Entity Framework Core.
User model:
public class User
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string PasswordHash { get; set; }
public ICollection<Order> Orders { get; set; }
}
Order model:
public class Order
{
[Key]
public int Id { get; set; }
[Required]
public string Test { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
Context:
public DbSet<User> Users { get; set; }
public DbSet<Order> Orders { get; set; }
public DatabaseContext(DbContextOptions options) : base(options)
{
//
}
I get an error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
when I'm trying to add orders to user with this code:
public void Test(User user)
{
user.Orders.Add(new Order() { Test = "test" });
_context.SaveChanges();
}
The only solution was this but the problem is that the ICollection<Order> Orders
count 0 every time:
private ICollection<Order> _orders;
public virtual ICollection<Order> Orders
{
get { return _orders ?? (_orders = new Collection<Order>()); }
set { _orders = value; }
}
I tried to make ICollection<Order>
and User
virtual
, but the error stays the same.
Thanks for your answers.
Remove collection initialisation from class and add order in the following way:
public void Test(User user)
{
_context.Orders.Add(new Order() { Test = "test", User = user });
_context.SaveChanges();
}
Try this:
public void Test(User user)
{
_context.Orders.Add(new Order { Test = "test", UserId=user.Id});
_context.SaveChanges();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.