1

I've got Entity Framework Code First Entities:

public class Customer
{
   public long Id { get; set; }
   public ICollection<ServiceAccount> Accounts { get; set; }
}

public class Service
{
   public long Id { get; set; }
}

public class ServiceAccount
{
   public long Id { get; set; }
   public Customer Customer { get; set; }
   [Required()]
   public Service Service { get; set; }
}

It is supposed that a Customer has some Accounts for the Services. But there can be some default Accounts, which are not bounded to any Customer. And each Account is used for a concrete Service. This Entities have the following Configuration:

// Customer Configuration:
base.ToTable("Customers");
base.HasKey(x => x.Id);
base.HasMany(x => x.ServiceAccounts)
    .WithOptional(x => x.Customer)
    .WillCascadeOnDelete();
// For Service:
base.ToTable("Services");
base.HasKey(x => x.Id);
// For Account:
base.ToTable("Accounts");
base.HasKey(x => x.Id);
base.HasOptional(x => x.Customer)
    .WithMany(x => x.Accounts);
base.HasRequired(x => x.Service)
    .WithMany();

The problem is, when I load a Customer, all his Accounts are loaded too, but they have their Service set to null. Why it is not loaded?

Thanks in advance

3
  • How are you loading the customers - could this be an eager vs lazy loading issue? msdn.microsoft.com/en-us/data/jj574232.aspx Commented Aug 11, 2015 at 8:03
  • Show us the code where you get the data. Commented Aug 11, 2015 at 8:04
  • I load them like this: IQueryable<Customer> customers = Customers.Include(x => x.Accounts); How can I include Accounts' Services? Commented Aug 11, 2015 at 8:23

2 Answers 2

3

You need to load the entities. Based on your comment:

IQueryable<Customer> customers = Customers.Include(x => x.Accounts.Select(y => y.Service));

They should also be virtual if you want proxies for lazy loading... but for eager loading it's not necessary

Sign up to request clarification or add additional context in comments.

Comments

1

Lazy loading of related entities requires the framework to create a proxy of your entity. Try making your navigation properties virtual:

public class ServiceAccount
{
   public long Id { get; set; }
   public virtual Customer Customer { get; set; }
   [Required]
   public virtual Service Service { get; set; }
}

Alternatively, eager-load the properties with Include or you can even explicitly load them with Load.

For more information, see https://msdn.microsoft.com/en-us/data/jj574232.aspx

1 Comment

Making them virtual did not help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.