Entity Framework 6 One-To-Many Relationship without Navigation Property

c# ef-code-first entity-framework-6

Question

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);
1
4
5/23/2017 12:08:04 PM

Accepted Answer

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

[ForeignKey("AID")]
public virtual A InstanceOfClassA {get;set;}
1
3/7/2014 5:27:33 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow