对于我第一次使用 EF 代码的程序。过去我使用 linq to SQL en EF DbFirst。检索主记录时'我无法使用导航属性加载子记录。我得到一个空子记录,所有记录字段都是 0 或 null。
当我想应用急切加载时。.Include(x=>x.......) 没有显示我的导航。
我设置了以下课程:
public Record()
{
Shipping = new ShippingData();
Delivery = new DeliveryData();
Items = new List<Item>();
ImportDate = DateTime.Now;
}
[Key]
public int RecordId { get; set; }
public int ShippingId { get; set; }
public int DeliveryId { get; set; }
public DateTime ImportDate { get; set; }
public virtual ShippingData Shipping { get; set; }
public virtual DeliveryData Delivery { get; set; }
public virtual List<Item> Items { get; set; }
public virtual Collecting CollectingOrder { get; set; }
具有以下上下文:
public class TweemansContext : DbContext
{
public TweemansContext()
: base("xxxx")
{
}
public DbSet<Add.Record> Records { get; set; }
public DbSet<Add.ShippingData> Shipping { get; set; }
public DbSet<Add.DeliveryData> Delivery { get; set; }
public DbSet<Add.Item> ProductItems { get; set; }
public DbSet<Add.Kolli> Kolli { get; set; }
public DbSet<Add.Collecting> CollectingOrders { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Record>().HasRequired(s => s.Shipping)
.WithMany()
.HasForeignKey(s => s.ShippingId);
modelBuilder.Entity<Record>().HasRequired(d => d.Delivery)
.WithMany()
.HasForeignKey(d => d.DeliveryId);
modelBuilder.Entity<Record>().HasOptional(c => c.CollectingOrder)
.WithOptionalDependent(a => a.Record).Map(p => p.MapKey("CollectionID"));
}
}
交付类是一个公共类,如下所示:
public class DeliveryData
{
[Key]
public int DeliveryId { get; set; }
public virtual Record Record { get; set; }
....lots of public properties
现在,当我尝试使用延迟加载时,我的交付类的所有属性都为空,使用以下代码:
using (TweemansContext context = new TweemansContext())
{
var imported = (from record in context.Records
where record.ImportDate.Year == date.Year && record.ImportDate.Month == date.Month && record.ImportDate.Day == date.Day
select record).ToList();
foreach (var Record in imported)
{
string email;
string telnr;
CustomerService service = new CustomerService(connectionString);
**string servicenr = Record.Delivery.AccountNumber.Substring(2, 8);**
service.GetUserData(servicenr, out email, out telnr);
Record.Delivery.Email = email;
Record.Delivery.TelephoneNbr = telnr;
}
context.SaveChanges();
}
在带有 ** 的行上,我的调试器告诉我交付存在,但它的所有属性都是空的。
当想要按如下方式应用包含时,.include 没有显示我的导航:
var imported = (from record in context.Records.Include(x=>x.)
where
record.ImportDate.Year == date.Year
&& record.ImportDate.Month == date.Month
&& record.ImportDate.Day == date.Day
select record).ToList();
我做错了什么,或者我误解了哪一部分?