Home > Back-end >  Relations error in .NET Core using Entity Framework Core
Relations error in .NET Core using Entity Framework Core

Time:11-01

I created a relationship between Users and TodoItems, but when I try to add, I get the error shown below.

long id = 1;
var user = _context.Users.Find(id);
user.TodoItems.Add(todoItem);
await _context.SaveChangesAsync();

My models:

public class TodoItem
{
    public long Id { get; set; }
    public string? Name { get; set; }
    public bool IsComplete { get; set; }
    public User User { get; set; }
}

public class User
{
    public long Id { get; set; }
    public string? Name { get; set; }
    public ICollection<TodoItem>? TodoItems { get; set; }
}

The error I'm getting:

error: The User field is required.

I'm using Entity Framework Core with Ngpsql.

Why am I getting this error and how do I fix it?

CodePudding user response:

Is the TodoItems property of User loaded? Doesn't seem so and I'm not entirely sure how latest EF Core handles such a situation. You can try eager loading the collection to see if that helps

var user = _context.Users
    .Include( u => u.TodoItems )
    .FirstOrDefault( u => u.Id == id ); 

// check for null result
if( user is null )
{
    // invalid user id
}

Or you can set the User property of the ToDoItem

var user = _context.Users.Find(id); // you should check for null result
todoItem.User = user;
await _context.SaveChangesAsync();

If you don't need the user entity for anything else, you can just fudge it with a quick instantiation setting only the PK value(s):

todoItem.User = new User { Id = id };
await _context.SaveChangesAsync();

Still no guarantees the id is valid but you could either handle the thrown exception or check if it exists first without loading the entire entity from the backing store. For example, wrap the above in

if( _context.Users.Any( u => u.Id == id ) )
{
    ...
}
else
{
    // handle invalid user id
}
  • Related