Table relationships of the EF error model

0

Good morning, I'm new to ASP.NET MVC and I'm trying to make a simple application where I only have two tables, the first table is the author and the second is the table books. When I give you an author, it saves it in the database, but when I want to register a book, it makes an error.

System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details. '

InvalidOperationException: A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.

I have a foreign key that refers to authors in the book table:

Id_autor int foreign key references autor(ID)

This is my post method

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,nombrelibro")] libros libros)
    {
        if (ModelState.IsValid)
        {
            db.libros.Add(libros);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.Id = new SelectList(db.autor, "Id", "nombre", libros.Id);
        return View(libros);
    }

Try to do the following

if (ModelState.IsValid)
{
    libros.autor.Id = 1; 
    db.libros.Add(libros);
    b.SaveChanges();
    return RedirectToAction("Index");
}

But I also get the following error System.NullReferenceException: 'Object reference not set as an instance of an object.'

    
asked by nexer13 01.08.2018 в 01:48
source

1 answer

0

Your problem is in the Create Bind, where you are not past an "Id_autor", try this way:

public ActionResult Create([Bind(Include = "Id,nombrelibro,Id_autor")] libros libros)
    
answered by 17.08.2018 в 18:03