我有一個數據庫生成的應用程序,我不能修改(我可以添加表,視圖等,但我不能修改現有的表,向他們添加列) 。我使用一個Web應用程序工作,該應用程序使用BreezeJS通過OData協議允許Web應用程序的客戶端部分查詢數據。EF Code First現有的數據庫,映射一對多
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
中有任何相應的行。
基本上我需要的是具有可選的Parent
屬性參考父測量和Children
測量列表。
謝謝您的輸入。我嘗試過表分割的方法,但它有一個問題。因爲EF使用'INNER JOIN',所以'Measurement'沒有指定它的父指針,這意味着'Measurement_Parent'表中沒有相應的行,雖然對於我來說這個場景是有效的,因爲測量的父字段是可選的。 – RiZe
您只需要爲每個「Measure」行創建一個'Measure_Parent'記錄,將'Parent' ID值設置爲null – Moho