在获取父实体EFCore时加载子实体 [英] Load child entity on the fetch of the Parent entity EFCore
问题描述
我有以下型号.在使用find方法从数据库中获取父实体时,用子实体加载父实体的更好方法是什么?
I have the below model. What is the better way to load the parent entity with child entity at the time of fetching from the DB with find method?
父实体:
public class Client
{
public int Id { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public DateTime DateOfBirth { get; set; }
public Address Address { get; set; }
}
子实体:
public class Address
{
public int Id { get; set; }
public string FirstLine { get; set; }
public string SecondLine { get; set; }
public string Province { get; set; }
}
现在,当我尝试使用Find方法获取数据时,地址实体为空,但是当我在DB数据表中检查子表中的ID时也存在.
Now when I try to fetch the data using the Find method I got the address entity null, but when I check in the DB data exist for that ID in Child table too.
referenceContext.Clients.Find(client.Id);
有没有办法克服这个问题?当我获取父对象时,子实体的值也同时加载了父对象.
Is there a way to overcome this? When I fetch the parent object and at the same time the value of the child entity is also loaded with the parent.
注意:到目前为止,如果我先使用Include(i => i.Address)
,则只能加载子实体.
Notes: As of now, if I used the Include(i => i.Address)
then, and then, only I am able to load the child entity.
我已经使用了Include,但是如果获得父实体,是否还有其他选项可以加载子实体.
I already use the Include but is there any other option exist to load child entity if I get the parent entity.
referenceContext.Clients.Where(c => c.IsActive.Equals(true))
.Include(i => i.Address).ToList();
推荐答案
如您所说:
注意:到目前为止,如果我使用了 Include(i => i.Address),那么,只有那时,我才能加载子实体.
Notes: As of now, if I used the Include(i => i.Address) then, and then, only I am able to load the child entity.
是的!这是在EF Core中加载相关数据的最佳方法.
您进一步说:
我已经使用了Include,但是如果获得父实体,是否还有其他选项可以加载子实体.
是的!有!这称为延迟加载.要启用延迟加载,您必须将导航属性设置为 virtual ,如下所示:
Yes! There is! That is called Lazy loading. To enable lazy loading you have to make the navigation property virtual as follows:
public class Client
{
public int Id { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public DateTime DateOfBirth { get; set; }
public virtual Address Address { get; set; } // <-- Here it is
}
并且您必须按照以下步骤注册DbConext
:
And you have to register your DbConext
as follows:
services.AddDbContext<BloggingContext>(
b => b.UseLazyLoadingProxies() // <-- Here is it is
.UseSqlServer(myConnectionString));
UseLazyLoadingProxies()
方法可在 Microsoft.EntityFrameworkCore.Proxies nuget程序包.
UseLazyLoadingProxies()
method is available in the Microsoft.EntityFrameworkCore.Proxies nuget package.
注意:您不能为特定查询禁用延迟加载.因此,使用急切加载是在EF Core中加载相关数据的最佳方法.
Note: You cannot disable lazy loading for a certain query. So using Eager loading is the best way to load related data in EF Core.
这篇关于在获取父实体EFCore时加载子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!