I have a (sample) application with the following code:
public class Posts
{
[Key]
[Required]
public int ID { get; set; }
[Required]
pub
The ForeignKey just has to be Nullable to make it optional - virtual is separate, and only required for Lazy Loading.
A required relationship in declarative EF Code First:
public User User { get; set; }
[ForeignKey("User")]
public int UserId { get; set; }
An optional relationship in declarative EF Code First:
public User User { get; set; }
[ForeignKey("User")]
public int? UserId { get; set; }
You'll see it when you run update-database -verbose -f
:
ALTER TABLE [dbo].[MyTable] ALTER COLUMN [UserId] [int] NULL