Good afternoon! I'm new to ASP.NET and EF6. Developed earlier in PHP.
I created a project (ASP.NET MVC) using EF6 and NPGSQL. I picked up a little while creating the relationships between two tables but it worked. The persona table will have several countries (1: n). It follows SQL, Model and context.
SQL:
CREATE TABLE pais(
idpais character(3) NOT NULL,
nomepais character varying(100) NOT NULL,
CONSTRAINT pk_pais PRIMARY KEY (idpais),
CONSTRAINT ix_nomepais UNIQUE (nomepais)
)
CREATE TABLE persona
(
idpersona serial NOT NULL,
nomepers character varying(100) NOT NULL,
idpaispers character(3),
CONSTRAINT pk_persona PRIMARY KEY (idpersona),
CONSTRAINT fk_perspais FOREIGN KEY (idpaispers)
REFERENCES pais (idpais) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT ix_nomepers UNIQUE (nomepers)
)
Model Parents
[Table("pais",Schema="public")]
public class Pais
{
public Pais()
{
this.Persona = new HashSet<Persona>();
}
[Key]
[Column("idpais")]
[Display(Name = "Sigla")]
[DataType(DataType.Text)]
[StringLength(3)]
[Required]
public string IDPais { get; set; }
[Column("nomepais")]
[Display(Name = "Nome")]
[DataType(DataType.Text)]
[StringLength(100)]
[Index("ix_nomepais",IsUnique=true)]
[Required]
public string nomePais { get; set; }
public virtual ICollection<Persona> Persona { get; set; }
}
Model Person:
[Table("persona", Schema="public")]
public class Persona
{
[Key]
[Column("idpersona")]
public int IDPersona { get; set; }
[Column("nomepers")]
[Display(Name = "Nome")]
[DataType(DataType.Text)]
[StringLength(100)]
[Index("ix_nomepers", IsUnique = true)]
[Required]
public string nomePers { get; set; }
[Column("idpaispers")]
[Display(Name = "País")]
[DataType(DataType.Text)]
[StringLength(3)]
public string idpaisPers { get; set; }
public virtual Pais Pais { get; set; }
}
Context:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Persona>()
.HasRequired<Pais>(p => p.Pais)
.WithMany(e => e.Persona)
.HasForeignKey(e => e.idpaisPers);
}
When it comes to including a "persona", I purposely specify a country that is not registered, generating a Postgres foreign key violation error. But should the EF not validate before? Did I miss something or should I include a validation so that this error does not occur? Thanks in advance for anyone who can help.