Mapping one-to-Many entity with Fluent API

Asked

Viewed 836 times

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’t do the same with Foo, since only Bar reference Foo tables. So, how can I map a relationship one-to-Many with Fluent API, so that the foreign key is only on one side (unidirectional)?

I can’t get the demonstrative class Foo have a list of Bar.

1 answer

6

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?

  • 1

    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.

  • 1

    On the other hand, this should indicate that Foo has no Bar, is the property Bars.Count be equal to zero and not Bars was null.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.