实体框架代码优先的空外键

| 我有一个
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 ]\"}
    
已邀请:
您必须使外键可为空:
public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    public virtual Country Country { get; set; }
}
    
我喜欢这个(下):
public class User
{
    public int Id { get; set; }
    public int? CountryId { get; set; }
    [ForeignKey(\"CountryId\")]
    public virtual Country Country { get; set; }
}
因为EF在数据库表中创建了2个外键:CountryId和CountryId1,但是上面的代码解决了这个问题。     
我现在有同样的问题, 我有外键,需要将其设置为可为空, 为了解决这个问题,你应该把
    modelBuilder.Entity<Country>()
        .HasMany(c => c.Users)
        .WithOptional(c => c.Country)
        .HasForeignKey(c => c.CountryId)
        .WillCascadeOnDelete(false);
在DBContext类中 很抱歉很晚才回答你:)     

要回复问题请先登录注册