如何解决实体框架代码优先的空外键
| 我有一个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类中
很抱歉很晚才回答你:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。