How to allow null values on Foreign keys using EF?

c# entity-framework

Question

How can I use EF to allow null values on Foreign keys?

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; }
}

I'm getting this runningnot null on the non-dominant key.

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

Accepted Answer

How to allow null values on Foreign keys using EF?

If you intend to use the following strategy, your database table must permit nulls as well:

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 alter

[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 ? a field with the characters nullable. Make sure your database can nullify it as well.

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

Popular Answer

You must be using code, in my opinion. If so, you should add the following line to the context class's overridden version of OnModelCreating.

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

Okay, I take it you modified your post after I responded.

You may utilize

User ID int

This will inform EF that you are permitting a nullable relationship for your user ID.



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