How to allow null values on Foreign keys using EF?

c# entity-framework

Question

How to allow null values on Foreign keys using EF?

public class User
{
    public User() 
    { 
    }

    public int idUser; { get; set; }
    [Required]
    public string UserName { get; set; }
    public virtual Computer Computer{ get; set; }
}

public class Computer
{
    public Computer() 
    {
    }
    [Key, ForeignKey("User")]
    public int idUser{ get; set; }
    public string ComputerName {get;set;}
    public virtual User User { get; set; }
}

Running this I'm getting not null on the foreign key.

1
0
4/15/2014 2:40:45 PM

Accepted Answer

How to allow null values on Foreign keys using EF?

Your database table should allow nulls as well if you are planning to take the following approach:

change

public int idUser; { get; set; }
[Required]
public string UserName { get; set; }
public virtual Computer Computer { get; set; }

To

public int idUser; { get; set; }
[Required]
public string UserName { get; set; }
public virtual Computer Computer{ get; set; }

And change

[Key, ForeignKey("User")] 
public int idUser { get; set; }
public string ComputerName { get; set; }
public virtual User User { get; set; }

To

[Key, ForeignKey("User")] 
public int? idUser { get; set; }
public string ComputerName { get; set; }
public virtual User User { get; set; }

The ? character, makes a field nullable. Make sure it is nullable in your database as well.

-2
5/8/2017 9:34:59 AM

Popular Answer

I assume you are using code first. If that is the case then you override OnModelCreating in the context class and add the following line

modelBuilder.Entity<Computer>().HasOptional(c => c.User);

================ Ok, you changed your post after I posted my answer.

You can use

int? idUser

for your user ID, this will let EF know that you are allowing a nullable relationship.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow