【发布时间】:2017-07-18 00:35:31
【问题描述】:
我一直在尝试在 2 个实体之间建立可选的一对一关系,但未成功。我可以通过在 RTUDEVICE 表 DeviceId 上创建唯一约束来做到这一点,但我正在尝试通过 Fluent API 以“正确的方式”进行操作
我做错了什么?
关系说明:
一个 DEVICE 记录在 RTUDEVICE 表中可能只有一个记录。
实体:
下面是实际类的简化版本...
public partial class Device
{
public Int Id { get; set; }
public string DeviceName { get; set; }
public virtual RTUDevice RTUDevice { get; set; }
}
public partial class RTUDevice
{
public Int Id { get; set; }
public int DeviceId { get; set; }
public bool IsCRMAlarmDevice { get; set; }
public bool HasCustomRegisters { get; set; }
public bool HasGasQualityRegisters { get; set; }
public bool HistoryVerified { get; set; }
public virtual Device Device { get; set; }
}
制图:
我使用各种在线示例进行了多次尝试,但均未成功...失败的代码已被注释掉。
public DeviceMap(DbModelBuilder modelBuilder)
{
ToTable("Device", "dbo")
.HasKey(m => m.Id);
Property(m => m.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.IsRequired();
Property(m => m.DeviceName)
.IsUnicode(false)
.HasMaxLength(100)
.IsRequired()
.HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UX_Device_AlternateKey") { IsUnique = true }));
//modelBuilder.Entity<RTUDevice>()
// .HasOptional(e => e.Device)
// .WithRequired(e => e.RTUDevice)
// .WillCascadeOnDelete(true);
}
public RTUDeviceMap(DbModelBuilder modelBuilder)
{
ToTable("RTUDevice", "dbo")
.HasKey(m => m.Id);
Property(m => m.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.IsRequired();
Property(e => e.DeviceId)
.IsRequired();
Property(e => e.IsCRMAlarmDevice )
.IsRequired();
Property(e => e.HasCustomRegisters)
.IsRequired();
Property(e => e.HasGasQualityRegisters)
.IsRequired();
Property(e => e.HistoryVerified)
.IsRequired();
// One-to-Zero-or-One relationship
//modelBuilder.Entity<RTUDevice>()
// .HasOptional(e => e.Device)
// .WithRequired(e => e.RTUDevice)
// .WillCascadeOnDelete(true);
// One-to-Zero-or-One relationship
//modelBuilder.Entity<RTUDevice>()
// .HasRequired(e => e.Device)
// .WithMany()
// .HasForeignKey(c => c.DeviceId)
// .WillCascadeOnDelete(true);
}
【问题讨论】:
-
从
RTUDevice中删除DeviceId属性并使用MapKeyfluent API - 请参阅here
标签: c# entity-framework code-first one-to-one