Data Annotation - error ratio 1:1

Asked

Viewed 87 times

1

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

It doesn’t 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 in the CieloRecorrencia place:

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

tried with Fluent API

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

What happens: he makes the reference to

CieloToken.CieloTokenId = CieloRecorrencia.CieloRecorrenciaId

and the right thing would be:

CieloToken.CieloTokenId = CieloRecorrencia.CieloTokenId
  • Recurrence can have 0 or 1 Tokens, that’s it?

  • that... but in practice will always have...1-1

  • Actually in practice one has to exist before the other. I believe it is recurrence. So I will answer based on this.

  • you are right the logic would be to put the Recursion id in the token, since it is generated later, I will change my model...

  • 1

    The principle is the same as it is in the answer. I think there is not much secret.

1 answer

2


The 0.. 1 to 1 modeling in the Entity Framework is a little weird. The right one is like 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; }
}

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

  • can’t boot that column, it comes from the database.. and in token I don’t have a column Cielorecorrenciatokenid

  • but if it’s the only option I can reverse where to save the key.....

  • Yes, so I asked you if it was the recurrence that had 0 or 1 Tokens. Actually it is the Token that can have 0 or 1 recurrences.

Browser other questions tagged

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