Map one-to-many entity with Fluent API

3

I have two classes, as an example below:

public class Foo
{
     public virtual int Chave {get; set;}
     public virtual List<Bar> Bar {get; set;}
}

public class Bar
{
    public virtual int Chave {get; set;}
    public virtual Foo Foo {get; set;}
}

I can map Bar to see Foo , but I can not do the same with Foo , since only Bar reference Foo in tables. So how can I map a one-to-many relationship with the Fluent API , so the foreign key is only one-way (unidirectional)?

I can not get the demo class Foo to have a list of Bar .

    
asked by anonymous 12.10.2014 / 02:20

1 answer

6

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

    
12.10.2014 / 16:57