In addition to mapping the one-to-many relationship it is necessary to map the key fields, since they do not follow the Entity Framework convention. This would not be necessary if they 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 automatically done by the Entity Framework if both classes were 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 you can find good tutorials on the Entity Framework