RavenDb的“包含”是否支持构造文档ID,而不仅仅是选择一个?

时间:2018-12-10 16:35:35

标签: ravendb

此代码无法正常工作。具体而言,似乎对Include的调用并未导致将任何其他文档添加到会话中。因此,Load各自花费了完整的数据库命中。这是RavenDb 3.5。

我找不到实际以这种方式使用Include的示例。它们似乎都发出一个“选择器”,该“选择器”用于在文档上查找成员,并且该成员持有要包括的文字文档ID。而我正在构造文档ID并将其作为字符串返回。

session.Query<Coil>()
    .Include(c => nameof(CoilState) + "/" + id)
    .Include(c => nameof(CoilExt) + "/" + id)
    .Include(c => nameof(Material) + "/" + c.MaterialCode)
    .Where(c => c.CoilId == id)
    .ToList()
    .Select(c =>
        Coil_Dto.ToCoilDto(
            c
            , session.Load<CoilState>(nameof(CoilState) + "/" + c.CoilId)
            , session.Load<CoilExt>(nameof(CoilExt) + "/" + c.CoilId)
            , session.Load<Material>(nameof(Material) + "/" + c.MaterialCode)
        )
    )
    .SingleOrDefault()

我的问题是:Include可以这样使用吗?如果没有,是否有某种方法可以使用我构造的ID来实现“包含”功能?

1 个答案:

答案 0 :(得分:1)

听起来您想使用Lazy,而不是Include。


包含

.include方法应该在包含ID的对象上传递属性的名称。

// Good:
// Note that StateId, ExtId, and MaterialId are all properties on our Coil class.
session.Query<Coil>()
   .Include(c => c.StateId)
   .Include(c => c.ExtId)
   .Inclide(c => c.MaterialId);

// Bad:
session.Query<Coil>
   .Include(c => "CoilStates/123")
   .Include(c => "CoilExts/456")
   .Include(c => "Materials/789")

简而言之,请确保您的.include调用已通过 Coil类的属性名称传递。这些属性应包含作为其他文档ID的字符串值。然后将它们全部加载到数据库中。


懒惰

如果“包括”对您的情况没有意义,但是您仍然希望在单个数据库调用中加载完全不同的对象,请使用lazy API

// Lazily load the coil. No DB trip yet.
var lazyCoil = session.Query<Coil>()
   .Where(...)
   .Lazily();

// Lazily load a CoilState. No DB trip yet.
var lazyCoilState = session.Advanced.Lazily.Load<CoilState>("CoilStates/123");

// Lazily load a Material. Still no DB trip.
var lazyMaterial = session.Advanced.Lazily.Load<Material>("Materials/456");

// Grab one of the values. This will fetch all lazy loaded items in 1 trip.
var coil = lazyCoil.Value;

// Grab the other values. No DB trip needed; they're already loaded!
var coilState = lazyCoilState.Value;
var material = lazyMaterial.Value;