Data Annotation - error ratio 1: 1

1

I'm trying to make a 1 to 1 ratio. Apparently it would be something simple but my system is getting lost in this relationship;

It does not make a mistake, but the relationship is wrong:

Model:

public class CieloRecorrencia
 {
       [Key]
       public int CieloRecorrenciaId { get; set; }

       [ForeignKey("CieloTokenId")]
       public int CieloTokenId { get; set; }

       public virtual CieloToken CieloToken { get; set; }
}

    public class CieloToken
    {
        [Key]
        public int CieloTokenId { get; set; }

        public virtual CieloRecorrencia CieloRecorrencia { get; set; }
    }

I tried to CieloRecorrencia put:

[ForeignKey("CieloToken")]
public int CieloTokenId { get; set; }

I tried with Fluent API

    modelBuilder.Entity<CieloRecorrencia>()
      .HasOptional(s => s.CieloToken) // Mark Address property optional in Student entity
      .WithRequired(ad => ad.CieloRecorrencia);

What happens: it does the

CieloToken.CieloTokenId = CieloRecorrencia.CieloRecorrenciaId

and the correct one would be:

CieloToken.CieloTokenId = CieloRecorrencia.CieloTokenId
    
asked by anonymous 04.04.2016 / 21:27

1 answer

2

The modeling 0..1 to 1 in the Entity Framework is a little weird. The correct way is this:

public class CieloRecorrencia
{
     [Key]
     public int CieloRecorrenciaId { get; set; }

     // Este aqui não precisa.
     // [ForeignKey("CieloTokenId")]
     // public int CieloTokenId { get; set; }

     public virtual CieloToken CieloToken { get; set; }
}

public class CieloToken
{
    [Key, ForeignKey("CieloRecorrencia")]
    public int CieloRecorrenciaId { get; set; }

    public virtual CieloRecorrencia CieloRecorrencia { get; set; }
}

Actually CieloToken has a primary key that is foreign at the same time. This is the only way to ensure that a recurrence record will have only one Token.

    
04.04.2016 / 21:43