我有以下表结构:在代码优先1对零关系
用户:
用户ID
名称
CountryId
国家
CountryId
名称
其中表用户的CountryId是国家/地区表的外键。
在代码中,我有以下实体:
public class User
{
public int Id{get; set;}
public int CountryId {get; set;}
public virtual Country Country {get; set;}
public string Name {get; set;}
}
public class Country
{
public int Id {get; set;}
public string Name {get; set;}
}
表国家存储用户可以属于10个可用的国家名单。不要为了数据库模型而杀了我,它必须是这样,遗留问题。
的关系被定义为通过流畅API如下:
modelBuilder.Entity<User>()
.HasRequired<Country>(c => c.Country)
.WithMany()
.HasForeignKey(c => c.CountryId);
的问题是每一次我尝试插入一个新的用户进入数据库时,模型中定义试图插入一个新进入该国表,以及和我得到以下错误:
Cannot insert the value NULL into column 'id', table '.countries'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated.
为什么EF试图插入新记录到该国表,以及我怎样才能解决这个问题,只插入一个新的用户和更新用户的国家已有国家的名单?
你能证明只需插入用户的代码? –
你是对的。问题是插入用户时,而不是像下面这样做:var country = ctx.Countries.FirstOrDefault(c => c.Id == countryId); user.Country = country;我在做user.Country =新国家{Id = countryId;名称=“bla”},这是不正确的,因为基本上我正在创建一个新的国家。 – Elena
凉爽。为了记录,你不需要从上下文中选择国家,你可以设置'user.CountryId = countryId'。 –