How do I define Foreign Key Optional Relationships in FluentAPI/Data Annotations with the Entity Framework?

前端 未结 4 2084
轻奢々
轻奢々 2020-12-31 00:16

I have a (sample) application with the following code:

public class Posts
{

    [Key]
    [Required]
    public int ID { get; set; }

    [Required]
    pub         


        
4条回答
  •  轮回少年
    2020-12-31 01:13

    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
    

提交回复
热议问题