Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework HasOptional In Data Annotations

How do I make the object VirtualTerminal optional in the code below ? Do I have to remove VirtualTerminal and only use VirtualTerminalId ?

[Table("Computer")]
public    class Computer :Device
{
    //public int Id { get; set; }
    public string OperatingSystem { get; set; }
    public string OS_LicenseKey { get; set; }
    public VirtualTerminal VirtualTerminal { get; set; }
    public int? VirtualTerminalId { get; set; }       
}
like image 734
Bill Greer Avatar asked Dec 16 '25 17:12

Bill Greer


1 Answers

Explicitly specifying the optional relationship should be unnecessary. Entity Framework conventions should detect VirtualTerminalId as the foreign key for the relationship, or you can use the ForeignKey data annotation over the VirtualTerminal navigation property:

[ForeignKey("VirtualTerminalId")]
public VirtualTerminal VirtualTerminal { get; set; }

Because VirtualTerminalId is nullable, Entity Framework will register the relationship as optional.

There are good explanations here and here.

like image 51
dotnetesse Avatar answered Dec 19 '25 11:12

dotnetesse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!