C# 保存包含由外键链接的集合的实体时发生EF错误
我的问题如下 我收到一个EF异常,并显示以下消息: 操作失败:无法更改关系,因为 一个或多个外键属性不可为空。当 对关系进行更改时,相关的外键属性为 设置为空值。如果外键不支持空值, 必须定义新关系,外键属性必须为 指定了另一个非空值,或者必须为不相关的对象 删除 对于这个异常,我可以自己判断出EF试图将null值设置为不可为null的int字段类型 以下是我的背景:C# 保存包含由外键链接的集合的实体时发生EF错误,c#,mysql,entity-framework,C#,Mysql,Entity Framework,我的问题如下 我收到一个EF异常,并显示以下消息: 操作失败:无法更改关系,因为 一个或多个外键属性不可为空。当 对关系进行更改时,相关的外键属性为 设置为空值。如果外键不支持空值, 必须定义新关系,外键属性必须为 指定了另一个非空值,或者必须为不相关的对象 删除 对于这个异常,我可以自己判断出EF试图将null值设置为不可为null的int字段类型 以下是我的背景: [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfigurati
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class RealEstDBContext : DbContext
{
#region Constructors
public RealEstDBContext()
: base("RealEstDBContext")
{
}
#endregion
#region DBSets
public DbSet<Caracteristic> Caracteristics { get; set; }
public DbSet<CaracteristicGroup> CaracteristicGroups { get; set; }
public DbSet<Parameter> Parameters { get; set; }
public DbSet<Property> Properties { get; set; }
public DbSet<PropertyType> ProertyTypes { get; set; }
public DbSet<Caption> Captions { get; set; }
#endregion
}
为什么不起作用。您不需要自己添加[ForeignKey]属性。尝试将您的特征模型更改为:
public class Caracteristic
{
#region Properties
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
public string Description { get; set; }
public int CaracteristicGroupId { get; set; }
public virtual CaracteristicGroup Group { get; set; }
#endregion
}
您不需要自己添加[ForeignKey]属性。尝试将您的特征模型更改为:
public class Caracteristic
{
#region Properties
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
public string Description { get; set; }
public int CaracteristicGroupId { get; set; }
public virtual CaracteristicGroup Group { get; set; }
#endregion
}
public class Caracteristic
{
#region Properties
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
public string Description { get; set; }
public int CaracteristicGroupId { get; set; }
public virtual CaracteristicGroup Group { get; set; }
#endregion
}