I try to add a list of subCategories from a book to a book the models:
public partial class Libro : Entidad
{
public string Titulo { get; set; }
public string Autor { get; set; }
public string ISBN { get; set; }
public string Descripcion { get; set; }
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString ="{0:C2}", ApplyFormatInEditMode = false)]
public decimal Precio { get; set; }
public int? Ano { get; set; }
public string Editorial { get; set; }
public string Edicion { get; set; }
public int Cantidad { get; set; }
public string UsrCr { get; set; }
public DateTime? FechaCr { get; set; }
public virtual ICollection<SubCategoria> SubCategorias { get; set; }
public virtual ICollection<LibroFoto> LibroFotos { get; set; }
}
public class SubCategoria : Entidad
{
public string Nombre { get; set; }
public string Descripcion { get; set; }
public int? CategoriaId { get; set; }
public virtual Categoria Categoria { get; set; }
public virtual ICollection<Libro> Libros { get; set; }
}
The controller
code when I try to create a book:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,Titulo,Autor,ISBN,Descripcion,Precio,Ano,Editorial,Edicion,Cantidad,UsrCr,FechaCr")] Libro libro)
{
if (ModelState.IsValid)
{
var listaSubCategorias = (IEnumerable<SubCategoria>)Session["SubCategoria"];
libro.LibroFotos = (List<LibroFoto>)Session["Libro"];
foreach (SubCategoria item in listaSubCategorias)
{
libro.SubCategorias.Add(item);
}
db.Libros.Add(libro);
await db.SaveChangesAsync();
Session["SubCategoria"] = new List<SubCategoria>();
return RedirectToAction("Index");
}
return View(libro);
}
and the error on the screen:
Thank you .. !!