【发布时间】:2014-02-01 04:07:00
【问题描述】:
我有一个由我无法修改的应用程序生成的数据库(我可以添加表、视图等,但我不能修改现有表,向它们添加列)。我在一个 Web 应用程序上工作,它使用 BreezeJS 允许 Web 应用程序的客户端部分通过 OData 协议查询数据。
Measurement 表结构如下:
MeasurementId INT
DeviceId INT FOREIGN KEY REFERENCES Devices (DeviceId)
Name VARCHAR,
PRIMARY KEY (MeasurementId)
我需要添加可空的ParentId自引用外键,因为我无法修改现有表,所以我创建了一个新表Measurement_Parent:
MeasurementId INT FOREIGN KEY REFERENCES Measurements (MeasurementId),
ParentId INT FOREIGN KEY REFERENCES Measurements (MeasurementId),
PRIMARY KEY (MeasurementId)
我有以下实体:
public partial class Measurement
{
public Measurement()
{
this.Children = new List<Measurement>();
}
public Int32 MeasurementId { get; set; }
public virtual Measurement Parent { get; set; }
public Int32 DeviceId { get; set; }
public virtual Device Device { get; set; }
public String Name { get; set; }
public virtual ICollection<Measurement> Children { get; set; }
}
现在是棘手的部分。我尝试了许多不同的方法来使其正常工作,但没有成功。我的实体的当前EntityTypeConfiguration 如下所示:
// Primary Key
this.HasKey(m => m.MeasurementId);
// Table & Column Mappings
this.Property(t => t.MeasurementId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
// Table & Column Mappings
this.ToTable("Measurement");
this.Property(m => m.MeasurementId);
this.Property(m => m.DeviceId);
this.Property(m => m.Name);
// Relationships
// Each measurement references device performing the measurement.
this.HasRequired(d => d.Device)
.WithMany(m => m.Measurements)
.HasForeignKey(d => d.DeviceId);
// Each measurement can have optional parent.
this.HasOptional(measurement => measurement.Parent)
.WithMany() // .WithMany(measurement => measurement.Children) ??
.Map(m =>
{
m.MapKey("ParentId");
m.ToTable("Measurement_Parent");
});
不幸的是,这在加载我的应用程序时给了我奇怪的错误:
Metadata query failed for: api/EDW/Metadata; The specified table 'Measurement_Parent' was not found in the model. Ensure that the table name has been correctly specified.
我不知道为什么会发生这种情况,因为桌子 在那里。我尝试将这两个表映射到一个实体(表拆分),但是因为 ParentId 可以是 NULL 和 EF 生成 INNER JOIN 而不是 LEFT OUTER JOIN 用于此映射,它不起作用,因为 Measurement 中的某些行表被省略,因为它们在Measurement_Parent 中没有任何对应的行。
基本上我需要的是参考父测量和Children 测量列表的可选Parent 属性。
【问题讨论】:
标签: c# entity-framework ef-code-first