我将尝试仅将模型的相关部分放在这里,因为有相当多的类。希望这足以捕捉问题:EF6代码首先,多个级联路径和奇怪的FK行为
public class Solve
{
public int SolveID { get; set; }
public int LocationID { get; set; }
public virtual Location Location { get; set; }
public int ProfileID { get; set; }
public virtual Profile Profile { get; set; }
public int BillID { get; set; }
public virtual Bill Bill { get; set; }
public int? PanelID { get; set; }
public virtual Panel Panel { get; set; }
}
public class Location
{
public int LocationID { get; set; }
[Index]
[StringLength(48)]
public string Name { get; set; }
[Index]
public State State { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public virtual List<Profile> Profiles { get; set; }
}
public class Profile
{
public int ProfileID { get; set; }
public int LocationID { get; set; }
public virtual Location Location { get; set; }
public double Capacity { get; set; }
public virtual List<ProfileSample> ProfileSamples { get; set; }
}
public class ProfileSample
{
[Key, ForeignKey("Profile")]
[Column(Order = 1)]
public int ProfileID { get; set; }
public virtual Profile Profile { get; set; }
[Key]
[Column(Order = 2)]
[DataType(DataType.Date)]
public DateTime Date { get; set; }
[Key]
[Column(Order = 3)]
public TimeSpan TimeOfDay { get; set; }
public double SampleValue { get; set; }
}
所以这是所有工作正常,直到我介绍了Solve
类,此时它开始抱怨“多阶路径”。我添加了以下上下文,它似乎是确定从那时起:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Solve>()
.HasRequired(s => s.Location)
.WithRequiredDependent()
.WillCascadeOnDelete(false);
}
除了它是不正确行为:
using (Model.BlueData bd = new Model.BlueData())
{
Random rng = new Random();
s = new Model.Solve()
{
Location = bd.Locations.Find(rng.Next(0, bd.Locations.Count())),
Bill = bd.Bills.Find(rng.Next(0, bd.Bills.Count())),
Profile = bd.Profiles.Find(rng.Next(0, bd.Profiles.Count()))
};
bd.Solves.Add(s);
bd.SaveChanges();
s = bd.Solves
.Where(u => u.SolveID == s.SolveID)
.Include(u => u.Location)
.Include(u => u.Profile)
.Include(u => u.Profile.ProfileSamples)
.Include(u => u.Bill)
.FirstOrDefault();
}
所以上面的代码只是产生一个随机Solve
对象,将其添加到数据上下文中,然后再次将其与所有关联的数据一起检索。这当然有一个更优雅的方式,但现在这只是测试代码,以确保我的应用程序的其他部分正在工作。
因此如预期,当我创建Solve s
对象,s.Location
是一个特定的位置,用ID,比方说,1609
,当然s.LocationID
和s.SolveID
的都等于0
。
将其添加到数据上下文并保存更改后,s.SolveID
等于位置的ID(在此示例中为1609
)。这很奇怪。我尝试在Solve
类中添加[Key]
属性到SolveID
和[ForeignKey("Location")]
到LocationID
,但它没有区别。
我尝试了各种方法,如从Solve
中删除Profile
或从位置中删除List<Profile> Profiles
。我现在不记得了,但有几件事情可以纠正设置为位置ID行为的s.SolveID
。
但是,这些属性都是有原因的,如果可能的话,我宁愿不删除它们只是为了得到这个工作。我不明白为什么会发生这种情况,或者如何正确纠正。我很感激任何帮助。
我认为,外键将需要重新添加,醚作为数据annotion(你已经tried-,我还以为是解决方案)或者可能使用流利的API来添加它。这也许可以解决它:http://stackoverflow.com/questions/21229373/ef-foreign-key-using-fluent-api –