Foreign key can be null in Entity?

5

I'm having a hard time on a project. I have created two tables ( Union and School ), with% of the Union table being PK in the School . But this FK can be null, meaning the School can belong to a Union or not. Well, here's my problem. I generated the mapping in the Entity Framework and when trying to insert a School without a Linked Union, it gives the following error:

    
asked by anonymous 30.07.2015 / 16:59

1 answer

7

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

You will have to define the field as accepting null's, putting ? on the secondary key (called nullable ):

public class Uniao
{
    public int UniaoId { get; set; }
    public int? EscolaId { get; set; }
    public virtual Escola Escola{ get; set; }
}
    
30.07.2015 / 17:24