c# EntityFramework 5在插入时丢失引用
本文关键字:引用 插入 EntityFramework | 更新日期: 2023-09-27 18:05:45
我有EF5,并希望(有…)建立一个多层应用程序。EF是我的持久层,我为我的客户端使用WCF。现在我的业务逻辑有一个问题,我不太明白。
我有一个方法应该保留一些东西。当我使用. savechanges()将Reservation发送到数据库时,一切都OK了。
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;
}
因此,在我执行此命令并调试它之后,将创建一个包含所有正确引用的新保留!但是当我再次尝试使用以下命令获取Reservation时:
//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;
我有学生和Korb属性设置为空值?在数据库中一切都是正确的。(存储正确的外键)
有人知道这种行为吗?
换句话说,当我试图再次使用另一个上下文获取Reservation时,我无法执行以下操作:
String test = newReservation.Student.Surename;
原因Student == null
您很可能启用了延迟加载(通过使Student
属性为虚拟)。如果是这种情况,你必须在从数据库加载时Include()
它。
var query = from it in context.Reservation.Include("Student")
select it;