entity framework代码 – 第一个空外键
我有一个User < Country模式。 用户属于一个国家,但可能不属于任何(空外键)。 
我如何设置? 当我尝试插入一个空国家的用户,它告诉我,它不能为空。
模型如下:
  public class User{ public int CountryId { get; set; } public Country Country { get; set; } } public class Country{ public List<User> Users {get; set;} public int CountryId {get; set;} } 
 错误: A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = Country_Users ]"} A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = Country_Users ]"} 
您必须使您的外键可以为空:
 public class User { public int Id { get; set; } public int? CountryId { get; set; } public virtual Country Country { get; set; } }