Can foreign key be null in Entity?

Asked

Viewed 601 times

5

I’m having a hard time in a project. I created two tables (Union and Schoolhouse), whereas the PK table Union is FK on the table Schoolhouse. But this FK may be void, i.e., the Schoolhouse may belong to a Union or not. Well, here’s my problem. I managed the mapping in the Entity Framework and when trying to insert a School without a linked Union, it gives the following error: inserir a descrição da imagem aqui

  • Here you have a problem just like yours. http://stackoverflow.com/questions/5668801/entity-framework-code-first-null-foreign-key

1 answer

7


The problem is when you define the field of your FK.

You will need to set the field to accepting null’s, placing the ? the secondary key (called nullable):

public class Uniao
{
    public int UniaoId { get; set; }
    public int? EscolaId { get; set; }
    public virtual Escola Escola{ get; set; }
}
  • 1

    Good 1+ would now put this answer.

  • 1

    I could leave PK in the pattern, no? UniaoId?

  • 1

    @Gypsy omorrisonmendez, corrected

Browser other questions tagged

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