In addition to mapping the relationship one-to-Many it is necessary to map the key fields, since they do not follow the convention of the Entity Framework. This would not be necessary if these were FooId
and BarId
or simply Id
.
public class Foo
{
//É uma boa prática inicializar as propriedades que são listas.
public Foo()
{
Bars = new List<Foo>();
}
public virtual int Chave {get; set;}
public virtual List<Bar> Bars {get; set;}//Já que é uma lista o nome deve ser Bars
}
public class Bar
{
public virtual int Chave {get; set;}
public virtual Foo Foo {get; set;}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Mapeamento das chaves:
modelBuilder.Entity<Foo>.HasKey(k => k.Chave);
modelBuilder.Entity<Bar>.HasKey(k => k.Chave);
//Mapeamento one-to-many
modelBuilder.Entity<Bar>().HasRequired<Foo>(s => s.Foo)
.WithMany(s => s.Bars)
.HasForeignKey(s => s.Chave);
}
The mapping would be done automatically by Entity Framework, if the two classes are defined as follows.
public class Foo
{
//É uma boa prática inicializar as propriedades que são listas.
public Foo()
{
Bars = new List<Foo>();
}
public virtual int Id {get; set;}
public virtual List<Bar> Bars {get; set;}//Já que é uma lista o nome deve ser Bars
}
public class Bar
{
public virtual int Id {get; set;}
public virtual int FooId {get; set;}
public virtual Foo Foo {get; set;}
}
Here can find good tutorials on the Entity Framework
Why "It is a good practice to initialize properties that are lists". What impact on not performing this initialization, or what benefit gain?
– Vinícius
To avoid having to always test whether the list is null before using it. We usually use the
for..each
to go through a list, if the list is initialized the code is executed without errors either the list has elements or not.– ramaral
On the other hand, this should indicate that
Foo
has noBar
, is the propertyBars.Count
be equal to zero and notBars
wasnull
.– ramaral