延迟加载实体,引用正在加载,但实体属性未加载



我仍在 EF 学习过程中,我正在尝试更熟悉 EF 延迟加载。

请考虑以下类和测试:

[Table("Tenant")]
public class  Tenant : IEntity
{
    public int Id { get; set; }
    public virtual string Name { get; set; }
    [Key]
    public string Guid { get; set; }
    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<CaseType> CaseTypes { get; set; }
    public Tenant()
    {
        Users = new List<User>();
        CaseTypes = new List<CaseType>();
    }
}

和测试:

    [Test]
    public void TenantLazyLoading()
    {
        var tenant = _applicationContext.Tenants.Create();
        tenant.Guid = "d176dc7c-6b96-4ab6-bddf-ce5a12024c39";
        _applicationContext.Tenants.Attach(tenant);
        Assert.AreEqual(1, tenant.Users.Count); // Pass, the navigation property users was loaded (lazy)
        Assert.AreEqual("localhost", tenant.Name); // Fail, the tenant name is not loaded
    }

延迟加载显然仅适用于导航属性,而不适用于租户属性。我把两个属性(UsersName)都做了虚拟的,但这似乎并不重要。

如何lazy load Tenant的本地属性?

这就是它的工作方式。如果手动创建实体并将其Attach到上下文中,则会告诉 EF 你不想加载实体的标量属性。

量属性没有延迟加载,您始终必须显式执行此操作,或者通过添加...

_applicationContext.Entry(tenant).Reload();

Attach后或将前三行替换为:

var tenant = _applicationContext.Tenants
    .Find(new Guid("d176dc7c-6b96-4ab6-bddf-ce5a12024c39"));

最新更新