I have a question about how I define the entries when I work with “Code First”.
I am defining the following class with these data annotations:
public class Producto
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProductoID { get; set; }
[ForeignKey("Parque"),Required]
public int FKParque { get; set; }
[ForeignKey("FKParque"), Required]
public virtual Parque Parque { get; set; }
public string Nombre { get; set; }
}
The question is:Should I put the data annotation “Required” in the navigation property “Parque”?
If I put the data annotation, when I try to do:
using (MiContexto contexto = new MiContexto()) {
Producto nuevoProducto = new Producto();
nuevoProducto.Nombre = "nuevo";
nuevoProducto.FKParque = 1;
contexto.Productos.Add(nuevoProducto);
contexto.SaveChanges();
}
An error occurs because the navigable property is null and is marked as required.
What would be the right approach?
Sorry if my English is not very good.
Thx.
I think placing the
requiredattribute on theFKParqueis sufficient. The navigation property isn’t populated until the object is saved/retrieved from the database, so could potentially be null, even if the foreign key can’t be.