5

I have 2 table: A and B with one-to-many relationship, these table were implemented in EF 6 as below:

public class A
{
    [Key]
    public int AID {get;set;}
    public string AName {get;set;}
}

public class B
{
    [Key]
    public int BID {get;set;}
    public string BName {get;set;}
    public int AID {get;set;}

    [ForeignKey("AID")]
    public A InstanceOfClassA {get;set;}
}

PROBLEM

When I retrieve B from context, InstanceOfClassA always null.

Assumption

Because there's no navigation property refer to B in A entity, therefore, entity framework doesn't lazy load A when retrieve B.

Expecting

Because I don't need to access B from A, therefore I want to get rid of navigation property in A but still preserve the ability of lazy load A from B.

NOTE

I saw a post from Map Many to Many relationship without navigation property but this doesn't suit in my case.

Is there anyway that I can force to lazy load A from B without using explicit include var b = context.B.Include(x => x.InstanceOfClassA);? Maybe Custom Convention

EDIT 1

I tried using convention as follow and still get no luck:

modelbuilder.Entity<B>()
    .HasRequired<A>(x => x.InstanceOfClassA);
Community
  • 1
  • 1
Doan Cuong
  • 2,594
  • 4
  • 22
  • 39
  • If you're going down vote my question, please take some time to leave a comment on what I did wrong. – Doan Cuong Mar 07 '14 at 02:49
  • I don't see anything wrong with this question. I spent a bit of time researching the same thing so that I wouldn't have to Include() on everything I was sending from a Service. I think I ended up creating a constructor in a partial class that loaded nav properties. Dunno if that works for you. – Chad McGrath Mar 07 '14 at 04:06
  • I though about manually loaded dependency too. But still looking for a solution that can be re used in future project. Custom Convention for example, but I go no idea on how to implement custom convention for this kind of relationship – Doan Cuong Mar 07 '14 at 04:13

1 Answers1

2

To get lazy loading working, you have to mark navigation property with virtual keyword:

[ForeignKey("AID")]
public virtual A InstanceOfClassA {get;set;}
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263