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

Does RavenDb's `Include` support constructing a document id, not just selecting one?

这里的代码没有按预期工作。具体来说,似乎对 Include 的调用不会导致任何额外的文档被添加到会话中。因此,Load 中的每一个都花费了完整的数据库命中。这是 RavenDb 3.5。

我找不到实际以这种方式使用 Include 的示例。它们似乎都发出一个 "selector" 用于在文档中查找成员,并且该成员包含要包含的文字文档 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 来实现 "include" 功能?

听起来您想使用 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 调用传递给线圈 class 上的 属性名称。这些属性应包含字符串值,这些值是其他文档的 ID。然后它们将全部加载到数据库中。


懒惰

如果 Include 对您的方案没有意义,但您仍想在单个数据库调用中加载不同的对象,请使用 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;