[英]EF code-first how to retrieve navigation-property with Entity?
Following is a data model wherein Entity A
has a navigation-property B
以下是一个数据模型,其中实体A
具有导航属性B
[Serializable]
public class X
{
[Key]
public int Id { get; set; }
}
[Serializable]
public class A : X
{
public List<B> B { get; set; }
}
[Serializable]
public class B : X
{
public int AId { get; set; }
public A A { get; set; }
}
Then, I'm trying to access table A from database as follows : 然后,我尝试从数据库访问表A,如下所示:
public class MyDatabaseContext : DbContext
{
Configuration.ProxyCreationEnabled = false;
}
public async Task<IEnumerable<T>> SelectAsync<T>() where T : X
{
using (MyDatabaseContext db = new MyDatabaseContext ())
{
var dataTable = db.Set<T>();
var temp = await dataTable.ToListAsync();
return temp;
}
}
This almost works except that for each instance of A
returned in the collection temp
the value of B
is null
. 除了对于集合temp
返回的A
每个实例, B
值为null
之外,这几乎可以工作。 Since each A
has a non null
B
in the database I'm surprised with the result of db.Set<T>()
由于每个A
在数据库中都有一个非null
B
,我对db.Set<T>()
的结果感到惊讶
Questions : 问题 :
db.Set<T>()
to return A
s with valid (non-null) B
s? 对于db.Set<T>()
以返回具有有效(非空) B
的A
我需要做什么? Update Based on suggestion of @Camilo Terevinto I tried the following, without luck 更新基于@Camilo Terevinto的建议,我尝试了以下操作,但没有运气
public class MyDatabaseContext : DbContext
{
Configuration.LazyLoadingEnabled = true;
}
Since you are explicitly disposing the context and you disabled lazy loading, you need to eagerly load the relation: 由于您要显式处理上下文,并且禁用了延迟加载,因此需要急于加载该关系:
await dataTable.Include("B").ToListAsync();
You will need to decide how you determine whether the current T
contains a navigational B
though. 您将需要决定如何确定当前T
是否包含导航B
I could not say why you get null
value. 我不能说为什么你得到null
值。 Normally, here is how one-to-one
are configured in Entity Framework. 通常,这是在实体框架中one-to-one
配置的方式。
When runing the following code with your SelectAsync
method, I get B
for every value of A
. 当使用SelectAsync
方法运行以下代码时,对于每个A
值,我都会得到B
public partial class X
{
public int Id { get; set; }
public virtual A A { get; set; }
public virtual B B { get; set; }
}
public partial class A
{
public A()
{
B = new HashSet<B>();
}
public int Id { get; set; }
public virtual X X { get; set; }
public virtual ICollection<B> B { get; set; }
}
public partial class B
{
public int Id { get; set; }
public int? AId { get; set; }
public virtual A A { get; set; }
public virtual X X { get; set; }
}
public partial class MyDatabaseContext : DbContext
{
...
public virtual DbSet<A> A { get; set; }
public virtual DbSet<B> B { get; set; }
public virtual DbSet<X> X { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<X>()
.HasOptional(e => e.A)
.WithRequired(e => e.X);
modelBuilder.Entity<X>()
.HasOptional(e => e.B)
.WithRequired(e => e.X);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.