我有以下表结构:
用户:
用户ID
名称
CountryId
国家
CountryId
名称
表user中的CountryId是Country表的一个对象键 在代码中,我有以下实体:
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);
问题是每次我尝试将新用户插入数据库时,定义的模型也会尝试在Country表中插入一个新条目,我收到以下错误:
无法将值NULL插入列'id',表'.countries';列不允许空值。 INSERT失败。\ r \ n语句已终止。
为什么ef会尝试在国家/地区表格中插入新记录,如何修复此问题以仅插入新用户并从已有国家/地区的列表中更新用户所在国家/地区?
答案 0 :(得分:2)
最有可能发生的事情是您要么添加没有国家/地区的用户: -
var user = new User()
{
Name = "Elena"
};
db.Users.Add(user);
如果是这种情况,您需要确保实际上可以添加没有国家/地区的用户。
首先,您需要更改流畅的API配置: -
modelBuilder.Entity<User>()
.HasOptional<Country>(c => c.Country)
.WithMany()
.HasForeignKey(c => c.CountryId);
您还需要在User nullable上创建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;}
}
或者,当您创建要插入的用户时,您正在做一些奇怪的事情,例如: -
var user = new User()
{
...
Country = new Country() ... // This will create a new country!
};
如果是这种情况,您希望将用户链接到现有国家/地区: -
var user = new User()
{
...
CountryId = countryId
};
答案 1 :(得分:0)
试试这个:
modelBuilder.Entity<User>()
.HasOptional<Country>(c => c.Country)
.WithMany()
.HasForeignKey(c => c.CountryId);
答案 2 :(得分:0)
试试这个:
public class Country
{
public int Id {get; set;}
public string Name {get; set;}
public ICollection<User> Users { get; set; }
}
和:
modelBuilder.Entity<User>()
.HasOptional<Country>(c => c.Country)
.WithMany(c=>c.Users)
.HasForeignKey(c => c.CountryId);