I am studying asp.net mvc with Code First….
I have a class called Livro:
Here its the code
public class Livro
{
[Key]
public int LivroId { get; set; }
[Required(ErrorMessage = "E necessario titulo")]
[MaxLength(100, ErrorMessage = "Titulo deve ter no maximo 100 caracteres")]
public string Titulo { get; set; }
public int AutorID { get; set; }
public virtual Autor Autor { get; set; }
}
As you can see it has a Navigation property called Autor and FK called AutorId. But I have this code on the Livro controller (I didn’t write this code, VS created based no my class).
[HttpPost]
public ActionResult Create(Livro livro)
{
if (ModelState.IsValid)
{
db.Livros.Add(livro);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.AutorID = new SelectList(db.Autores, "AutorId", "Nome", livro.AutorID);
return View(livro);
}
If i have [Required] on the Autor attribute, the modelState.IsValid becomes false because livro.Autor is null. So i must take it out.
But i was reading a book from Julia Lerman that its called “Programming EF Code-First” and
sometimes there is navigation properties with the [Required] attribute.
What am i missing here?
It’s probably because the View only refers to the
Livrofields, not theAutorand the model binder is unable to create theAutornavigation property. You can create fields for theAutor, using smth like this:However, this will become painful and maybe you only need to select the author from the list. I would add the
Requiredattribute to theLivro.AutorIDproperty only and leaveAutoras is.