在EF Core 2.2中使用代码优先时,我陷入困境。
我有一个实体:AirSensor,我需要与TemperatureSensors具有两个一对一的关系,因为AirSensor能够读取温度和露点温度。
因此我的代码在这里:
public class AirSensor
{
public long AirSensorId { get; set; }
public TemperatureSensor TemperatureSensor { get; set; }
public HumiditySensor Humidity { get; set; }
public Enthalpy EnthalpyCalc { get; set; }
public TemperatureSensor DewPointTemperatureSensor { get; set; }
public long TemperatureSensorId { get; set; }
public long HumiditySensorId { get; set; }
public long EnthalpyId { get; set; }
public long DewPointTemperatureSensorId { get; set; }
}
温度实体为:
public class TemperatureSensor
{
public long TemperatureSensorId { get; set; }
public string Name { get; set; }
public float CurrentValue { get; set; }
public DateTime LastUpdated { get; set; }
public ICollection<TemperatureMeasurement> Measurements { get; set; }
}
添加迁移后,一切正常,但是更新数据库失败:
执行DbCommand失败(17ms)[Parameters = [],CommandType ='Text',CommandTimeout = '30']
ALTER TABLE [AirSensors]添加约束[FK_AirSensors_TemperatureSensors_DewPointSensorId]外部键([DewPointSensorId])参考[TemperatureSensors]([TemperatureSensorId])在删除级联上; System.Data.SqlClient.SqlException(0x80131904):异类外键'FK_AirSensors_TemperatureSensors_DewPointSensorId'和表'AirSensors',列表中的cacada。关于删除无效动作或更新无效动作的说明,请修改外在密码。
但是,我在这里看不到问题,我只想拥有两个单独的一对一关系。
我想念什么?
非常感谢!
答案 0 :(得分:0)
使用AirSensor
配置Fluent API
,如下所示:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<AirSensor>().HasOne(ars => ars.TemperatureSensor)
.WithOne().HasForeignKey<AirSensor>(ars => ars.TemperatureSensorId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<AirSensor>().HasOne(ars => ars.DewPointTemperatureSensor)
.WithOne().HasForeignKey<AirSensor>(ars => ars.DewPointTemperatureSensorId)
.OnDelete(DeleteBehavior.Restrict);
}
现在它将按预期工作!