简体   繁体   English

实体框架代码优先导航属性返回空字段

[英]Entity Framework Code First navigational properties returning null fields

For a program I'm using EF code first for the first time. 对于程序,我是第一次使用EF代码。 In the past I used linq to SQL en EF DbFirst. 过去,我使用linq到SQL en EF DbFirst。 When retreiving the main record'I'm unable to load the subrecords using the navigational properties. 检索主记录时,'我无法使用导航属性加载子记录。 I get an empty subrecord with all record-fields are 0 or null. 我得到一个空的子记录,其中所有记录字段均为0或为null。

When I want to apply eager loading. 当我想应用渴望的加载时。 the .Include(x=>x.......) isn't showing my navigationals. .include(x => x .......)未显示我的导航。

I have set up the following classes: 我设置了以下课程:

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; }

with the following context: 具有以下上下文:

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"));
    }
}

the delivery class is a public class as wel as follows: 交付班是公共班,如下:

    public class DeliveryData
{
    [Key]
    public int DeliveryId { get; set; }
    public virtual Record Record { get; set; }

    ....lots of public properties

now when I try to use lazy loading all my properties of the delivery class are null using the following code: 现在,当我尝试使用延迟加载时,使用以下代码将交货类的所有属性设置为null:

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();
        }

on the rows with the ** my debugger is telling me that delivery exists but all of it's properties are null. 在带有**的行上,我的调试器告诉我传递已存在,但其所有属性均为null。

When wanting to apply an include as follows the .include isn't showing my navigation: 当要应用如下包含时,.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();

What am I doing wrong, or which part have i misuderstood?? 我做错了什么,或者我误解了哪一部分??

You must remove the initialization of the navigation references from the Record constructor, the initialization of the empty navigation collection is OK: 您必须从Record构造函数中删除导航引用的初始化,空的导航集合的初始化是可以的:

Shipping = new ShippingData(); // remove this line
Delivery = new DeliveryData(); // remove this line

Essentially these lines "overwrite" the loaded data with values that the constructors of ShippingData and DeliveryData set, probably the default values 0 and null . 本质上,这些行使用ShippingDataDeliveryData的构造函数设置的值“覆盖”加载的数据,可能是默认值0null

Side note about your remark " the .Include(x=>x.......) isn't showing my navigationals ". 关于您的备注“ .include(x => x .......)未显示我的导航的旁注 You need to put using System.Data.Entity; 您需要using System.Data.Entity; at the beginning of your code file to make the Include extension method available that takes a lambda expression as parameter. 在代码文件的开头,使Include扩展方法可用,该方法将lambda表达式作为参数。

When your debug stop there you should be getting a proxy class on Delivery. 当调试停止时,您应该在Delivery上获得一个代理类。 if you are no getting this you should enable lazy load on your context. 如果没有得到,则应该在上下文中启用延迟加载。 You can check here how to enable lazy load. 您可以在此处查看如何启用延迟加载。

If you don't want to enable lazy load you should use Include in your query to include the Delivery information. 如果您不想启用延迟加载,则应在查询中使用“包括”以包含“传递”信息。 Here you can have some info how to use include. 在这里,您可以获得一些有关如何使用包含的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM