C#EntityFramework 5在插入时丢失引用
我有EF5,并希望(有…)建立一个多层应用程序。EF是我的持久层,我为我的客户使用WCF。现在我的业务逻辑有一个问题,我不能完全理解 我有一个方法,应该保留一些东西。当我使用.SaveChanges()将预订发送到数据库时,一切都正常C#EntityFramework 5在插入时丢失引用,c#,entity-framework,insert,C#,Entity Framework,Insert,我有EF5,并希望(有…)建立一个多层应用程序。EF是我的持久层,我为我的客户使用WCF。现在我的业务逻辑有一个问题,我不能完全理解 我有一个方法,应该保留一些东西。当我使用.SaveChanges()将预订发送到数据库时,一切都正常 public bool bReservieren(Student oStudent, Korb oKorb, IEnumerable<Service> lServices, DateTime dtFrom, DateTime dtTo) {
public bool bReservieren(Student oStudent, Korb oKorb, IEnumerable<Service> lServices, DateTime dtFrom, DateTime dtTo)
{
try
{
BeachChaireModelContainer context = new BeachChaireModelContainer();
Reservierung newReservation = context.Reservation.Create();
//Tried it with newReservation.Student = oStudent; But there is an
//error cause of the different context´s so I search the correct Student
//again. (same with Korb)
newReservation.Student = context.Student.Find(oStudent.Kartennummer);
newReservierung.Korb = context.Korb.Find(oKorb.KID);
newReservierung.dtVON = dtFrom;
newReservierung.dtBIS = dtTo;
newReservierung = context.Reservation.Add(newReservation);
//This if isnt relevant yet. lService is null in my tests
if (lServices != null)
{
foreach (var item in lServices)
{
newReservation.Service.Add(context.Service.Find(item.SeID));
}
}
context.SaveChanges();
return true;
}
catch (Exception)
{ }
return false;
}
我将Student和Korb属性设置为空值?数据库中的一切都是正确的。(存储了正确的外键)
有人知道这种行为吗
换句话说,当我尝试在另一个环境下再次获得预订时,我无法执行以下操作:
//had to mention it is a new Methode with a new context, but this should
//be no Problem in my oppinion?
var query = from it in context.Reservation
select it;
String test = newReservation.Student.Surename;
原因Student==null您很可能启用了延迟加载(通过将
Student
属性设置为虚拟)。如果是这种情况,则从数据库加载时必须包含()
var query = from it in context.Reservation.Include("Student")
select it;