0

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?

3
  • You haven't shown the code where you get todoItem so I can only guess, but the error suggests that you need to set the User property on todoItem. You should probably also use an Include when you get the user to make sure that the todo items are loaded. Commented Oct 31, 2022 at 21:34
  • todoItem comes from the body of the POST request, TodoItem has a One-To-Many relationship with Users, so what I did is the same as the Entity Framework documentation Commented Oct 31, 2022 at 21:51
  • Check the incoming todoItem to see if the User property is set. If not, then you'll need to set it manually. Commented Oct 31, 2022 at 21:55

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, bro, the second code described by you worked, thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.