1
I want to make relationship one for many in EF where one and only Territory has several regions, but when analyzing the model in Power Tools it does not recognize.
Region
[Table("Regiao")]
public class Regiao
{
[Key]
[DisplayFormat(DataFormatString = "{0:0000}", ApplyFormatInEditMode = true)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long RegiaoID { get; set; }
[Display(Name = "Região")]
[Column(TypeName = "varchar")]
[StringLength(50, ErrorMessage = "O {0} deve ser de pelo menos {2} caracteres.", MinimumLength = 2)]
[Required(ErrorMessage = "Campo Obrigatório")]
public string RegiaoDescricao { get; set; }
[ForeignKey("FKTerritorioID")]
public long TerritorioID { get; set; }
public virtual Territorio Territorio { get; set; }
}
Territory
[Table("Territorio")]
public class Territorio
{
[Key]
[DisplayFormat(DataFormatString = "{0:0000}", ApplyFormatInEditMode = true)]
public long TerritorioID { get; set; }
[Required(ErrorMessage="Campo Obrigatório")]
public string TerritorioDescricao { get; set; }
public ICollection<Regiao> Regioes { get; set; }
}
Context
public class DbEmpresaContext : DbContext
{
public DbEmpresaContext()
: base("connDBEmpresaModelo")
{
}
public DbSet<Regiao> Regioes { get; set; }
public DbSet<Territorio> Territorios { get; set; }
}
Randrade, does the virtual have to stay in the collection only as in this snippet of code you changed? public virtual Territorio Territorio { get; set; } Another question, I’ve seen in codes where they only use the Data Annotations [Key] and [Foreignkey] to determine relationships, do not use navigation properties, this is correct?
– Kelly Soares
The
virtual
, Roughly speaking, it serves to return all regions to what the territory possesses, that is, when you look for it. You don’t need to use anottations for this. The EF generates automatically based on the name of the properties. If you want to ask a question about this, I will be happy to explain better.– Randrade