Entity framework code-first null foreign key

前端 未结 4 1384
梦如初夏
梦如初夏 2020-11-28 05:34

I have a User < Country model. A user belongs to a country, but may not belong to any (null foreign key).

How do I set this up? When I t

4条回答
  •  清酒与你
    2020-11-28 06:22

    I prefer this (below):

    public class User
    {
        public int Id { get; set; }
        public int? CountryId { get; set; }
        [ForeignKey("CountryId")]
        public virtual Country Country { get; set; }
    }
    

    Because EF was creating 2 foreign keys in the database table: CountryId, and CountryId1, but the code above fixed that.

提交回复
热议问题