1
Good afternoon ! I’m new to ASP.NET and EF6. I used to develop in PHP.
I created a project (ASP.NET MVC) using EF6 and NPGSQL. I got a little bit when creating 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 Pais
[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 Persona :
[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 foreign key violation error of Postgres. But shouldn’t EF validate before ? Was I wrong or should I include a validation to prevent this error ? Thank you in advance who can help.
Thanks for the clarification. But I came up with a layman’s question: If I have to do the validation, what is the purpose of "declaring" the relationships ?
– Renato
Take advantage of the lazy load features and work the objects at the application level. For example, a foreign relationship assignment, for example
persona.idPaisPers = 1
, is incorrect from the point of view of the Entity Framework, but valid if you dopersona.Pais = pais;
, beingpais
an object of the typePais
previously selected by the Entity Framework.– Leonel Sanches da Silva
Again, I thank you for your clarification. It became easier to understand.
– Renato