测量和观察之间存在一对一的关系,但观察结果有"之前" """"测量。只要我不需要导航属性从测量返回到观察,这就可以正常工作。实体无法解析Measurement.observation属性,导致normalizedValue属性引发NullPointer异常。
编辑:已编辑以尝试包含来自How can I set up two navigation properties of the same type in Entity Framework的评论,但仍无效。
public class Measurement
{
[Key]
public int measurementId { get; set; }
public int val1 { get; set; }
public virtual Observation observation { get; set; }
public float noramlizedValue { get { return val1 / observation.normalizationFactor; } }
}
public class Observation
{
[Key]
public int observationId { get; set; }
[Required]
public int beforeMeasId { get; set; }
public virtual Measurement before { get; set; }
[Required]
public int afterMeasId { get; set; }
public virtual Measurement after { get; set; }
public int normalizationFactor { get; set; }
}
public class Model1 : DbContext
{
public virtual DbSet<Observation> observations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Observation>()
.HasRequired(o => o.before)
.WithMany()
.HasForeignKey(o => o.beforeMeasId)
.WillCascadeOnDelete(true);
modelBuilder.Entity<Observation>()
.HasRequired(o => o.after)
.WithMany()
.HasForeignKey(o => o.afterMeasId)
.WillCascadeOnDelete(false);
}
}
class Program
{
static void Main(string[] args)
{
using (var db = new Model1())
{
db.Configuration.LazyLoadingEnabled = true;
var o1 = new Observation
{
before = new Measurement { val1 = 5 },
after = new Measurement { val1 = 10 },
normalizationFactor = 3
};
db.observations.Add(o1);
db.SaveChanges();
Console.WriteLine("Before: ");
Console.WriteLine(o1.before.noramlizedValue); // Raises null reference exception
Console.WriteLine("After: ");
Console.WriteLine(o1.after.noramlizedValue);
}
}