报错信息
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable.
When a change is made to a relationship,
the related foreign-key property is set to a null value.
If the foreign-key does not support null values,
a new relationship must be defined,
the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted
操作失败:无法更改关系,因为一个或多个外键属性不可为空。
当对关系进行更改时,相关的外键属性将设置为空值。
如果外键不支持空值,则必须定义新的关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象
举例代码
主表
public partial class Role
{
public Role()
{
Users = new HashSet<User>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class RoleConfiguration : EntityTypeConfiguration<Role>
{
public RoleConfiguration()
{
HasKey(x => x.Id);
}
}
从表
public partial class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int RoleId { get; set; }
public virtual Role Role { get; set; }
}
public class UserConfiguration : EntityTypeConfiguration<User>
{
public UserConfiguration()
{
HasKey(x => x.Id);
HasRequired(m => m.Role)
.WithMany(m=>m.Users)
.HasForeignKey(x => x.RoleId)
.WillCascadeOnDelete(true);
}
}
与EF6应该是类似逻辑的,虽然没试过
EFCore 级联删除微软官方文档
新增时保持属性值为 Guid.Empty即可,保存后即可获得连续的Guid
在SqlServer中使用的是newsequentialid()方法获取,其原理感兴趣的可以去深究下.
Property(x => x.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);