[英]Entity Framework 6 One-To-Many Relationship without Navigation Property
I have 2 table: A and B with one-to-many relationship, these table were implemented in EF 6 as below: 我有2个表:A和B有一对多的关系,这些表在EF 6中实现如下:
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. 当我从上下文中检索B
时, InstanceOfClassA
始终为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
. 因为没有导航属性参考A
实体中的B
,因此,实体框架在检索B
时不会延迟加载A
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
. 因为我不需要从A
访问B
,所以我想摆脱A
的导航属性但仍保留B
中延迟加载A
的能力。
NOTE 注意
I saw a post from Map Many to Many relationship without navigation property but this doesn't suit in my case. 我看过Map Many to Many关系中没有导航属性的帖子,但这不符合我的情况。
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);
无论如何,我可以强制从B
延迟加载A
而不使用显式include var b = context.B.Include(x => x.InstanceOfClassA);
? ? Maybe Custom Convention 也许定制会议
EDIT 1 编辑1
I tried using convention as follow and still get no luck: 我尝试使用惯例如下,仍然没有运气:
modelbuilder.Entity<B>()
.HasRequired<A>(x => x.InstanceOfClassA);
To get lazy loading working, you have to mark navigation property with virtual
keyword: 要使延迟加载工作,您必须使用virtual
关键字标记navigation属性:
[ForeignKey("AID")]
public virtual A InstanceOfClassA {get;set;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.