Home > other >  ArgumentException: The key value at position 0 of the call to 'DbSet<News>.Find' was
ArgumentException: The key value at position 0 of the call to 'DbSet<News>.Find' was

Time:02-26

This error is thrown when I try to edit my post. Here is my code

public async Task<IActionResult> Edit(string id)
    {
        if (id == null)
        {
            return NotFound();
        }
        // issue 
        var news = await _context.News.FindAsync(id);
        if (news == null)
        {
            return NotFound();
        }
        return View(news);
    }

the debugger stops the code at

var news = await _context.News.FindAsync(id);

code for my model is

public int id { get; set; }
    [Required(ErrorMessage = "Enter your name.")]
    public string Author { get; set; }
    [Required(ErrorMessage = "Enter the title.")]
    public string Title { get; set; }
    [Required(ErrorMessage = "Enter the issued date.")]
    [DataType(DataType.Date)]
    public DateTime IssueDate { get; set; }
    [Required(ErrorMessage = "Enter a message.")]
    [DataType(DataType.MultilineText)]
    public string Body { get; set; }

Any idea on how to fix this?

CodePudding user response:

According to the documentation:

FindAsync(Object[])

Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found, then null is returned.

Therefore, if the primary key in your case has int type, than the FindAsync() parameter should be the same type - int.

CodePudding user response:

The most reliable way would be

  var news = await _context.News.FirstOrDefaultAsync(i=>i.id==id);
  • Related