Не создается новая запись в таблицах с внешними ключами ASP Net Core model-view-controller

Когда открываю страницы Create таблиц без внешних ключей, ввожу данные в поля, затем нажав кнопку Create, запись создается. Где есть foreign key - не работает, в принципе не выдает ошибки. Использовалось логирование и вот что выдало:

test_norm_entities.Controllers.ContactsController: Warning: Failed to create a Contact due to invalid model state. test_norm_entities.Controllers.ContactsController: Error: Validation error in field IdIncNavigation: The IdIncNavigation field is required. test_norm_entities.Controllers.ContactsController: Error: Validation error in field IdAreaNavigation: The IdAreaNavigation field is required. test_norm_entities.Controllers.ContactsController: Error: Validation error in field IdWorkerNavigation: The IdWorkerNavigation field is required.

Код класса Contact

public partial class Contact
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Address is required.")]
    public string Address { get; set; } = null!;

    [Required(ErrorMessage = "Area is required.")]
    public int IdArea { get; set; }

    [Required(ErrorMessage = "Incident is required.")]
    public int IdInc { get; set; }

    [Required(ErrorMessage = "Worker is required.")]
    public int IdWorker { get; set; }

    public string? Complain { get; set; }

    public int Mark { get; set; } = 0;

    public virtual ICollection<App> Apps { get; set; } = new List<App>();

    public virtual Area IdAreaNavigation { get; set; } = null!;

    public virtual Inc IdIncNavigation { get; set; } = null!;

    public virtual Worker IdWorkerNavigation { get; set; } = null!;
}

Контекст данных

modelBuilder.Entity<Contact>(entity =>
{
    entity.HasKey(e => e.Id).HasName("PK__contact__3214EC07705C148B");

    entity.ToTable("contact");

    entity.Property(e => e.Id).ValueGeneratedNever();
    entity.Property(e => e.Address).HasColumnName("address");
    entity.Property(e => e.Complain).HasColumnName("complain");
    entity.Property(e => e.IdArea).HasColumnName("ID_area");
    entity.Property(e => e.IdInc).HasColumnName("ID_inc");
    entity.Property(e => e.IdWorker).HasColumnName("ID_worker");
    entity.Property(e => e.Mark).HasColumnName("mark");

    entity.HasOne(d => d.IdAreaNavigation).WithMany(p => p.Contacts)
        .HasForeignKey(d => d.IdArea)
        .OnDelete(DeleteBehavior.ClientSetNull)
        .HasConstraintName("FK__contact__ID_area__46E78A0C");

    entity.HasOne(d => d.IdIncNavigation).WithMany(p => p.Contacts)
        .HasForeignKey(d => d.IdInc)
        .OnDelete(DeleteBehavior.ClientSetNull)
        .HasConstraintName("FK__contact__ID_inc__47DBAE45");

    entity.HasOne(d => d.IdWorkerNavigation).WithMany(p => p.Contacts)
        .HasForeignKey(d => d.IdWorker)
        .OnDelete(DeleteBehavior.ClientSetNull)
        .HasConstraintName("FK__contact__ID_work__48CFD27E");
});

Контроллер

// GET: Contacts/Create
public IActionResult Create()
{
    _logger.LogInformation("Initiating creation of a new Contact.");
    ViewData["IdArea"] = new SelectList(_context.Areas, "Id", "Id");
    ViewData["IdInc"] = new SelectList(_context.Incs, "Id", "Id");
    ViewData["IdWorker"] = new SelectList(_context.Workers, "Id", "Id");
    return View();
}

// POST: Contacts/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Address,IdArea,IdInc,IdWorker,Complain,Mark")] Contact contact)
{
    if (ModelState.IsValid)
    {
        _logger.LogInformation("Creating a new Contact with Address: {Address}", contact.Address);
        _context.Add(contact);
        await _context.SaveChangesAsync();
        _logger.LogInformation("Contact with ID {Id} was created successfully.", contact.Id);
        return RedirectToAction(nameof(Index));
    }
    _logger.LogWarning("Failed to create a Contact due to invalid model state.");

    foreach (var state in ModelState)
    {
        foreach (var error in state.Value.Errors)
        {
            _logger.LogError("Validation error in field {Field}: {Error}", state.Key, error.ErrorMessage);
        }
    }
    ViewData["IdArea"] = new SelectList(_context.Areas, "Id", "Id", contact.IdArea);
    ViewData["IdInc"] = new SelectList(_context.Incs, "Id", "Id", contact.IdInc);
    ViewData["IdWorker"] = new SelectList(_context.Workers, "Id", "Id", contact.IdWorker);
    return View(contact);
}

Ответы (0 шт):