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.
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.
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.