MongoDB类映射

时间:2016-12-20 16:39:56

标签: c# mongodb mapping mongodb-.net-driver

我有以下数据结构

internal class FixtureNodeBase
{
  public FixtureNodeBase( string name, IEnumerable<FixtureNodeBase> children )
  {
    Name = name;
    Children = children.ToList().AsReadOnly();
  }

  public string Name { get; }

  public IReadOnlyList<FixtureNodeBase> Children { get; }
}

internal class FixtureNode : FixtureNodeBase
{
  public FixtureNode(
    string name,
    string assembly,
    string runnableName,
    IEnumerable<FixtureNodeBase> children )
    : base( name, children )
  {
    Assembly = assembly;
    RunnableName = runnableName;
  }

  public string Assembly { get; }

  public string RunnableName { get; }
}

internal class FixtureTree
{
  public FixtureTree( FixtureNodeBase root )
  {
    Root = root;
  }

  public FixtureNodeBase Root { get; }
}

internal class Build
{
  public Build( FixtureTree fixtures )
  {
    Fixtures = fixtures;
  }

  public FixtureTree Fixtures { get; }
}

我在映射后使用的数据结构

BsonClassMap.RegisterClassMap<Build>(
  cm =>
  {
    cm.MapMember( x => x.Fixtures );
    cm.MapCreator( x => new Build( x.Fixtures ) );
} );

BsonClassMap.RegisterClassMap<FixtureTree>(
  cm =>
  {
    cm.MapMember( x => x.Root );
    cm.MapCreator( x => new FixtureTree( x.Root ) );
} );

BsonClassMap.RegisterClassMap<FixtureNodeBase>(
  cm =>
  {
    cm.MapMember( x => x.Name );
    cm.MapMember( x => x.Children );
    cm.MapCreator( x => new FixtureNodeBase( x.Name, x.Children ) );
} );

BsonClassMap.RegisterClassMap<FixtureNode>(
  cm =>
  {
    cm.MapMember( x => x.Name );
    cm.MapMember( x => x.Assembly );
    cm.MapMember( x => x.RunnableName );
    cm.MapMember( x => x.Children );
    cm.MapCreator( x => new FixtureNode( x.Name, x.Assembly, x.RunnableName, x.Children ) );
} );

并抛出FixtureNode映射的异常:

  

&#34; System.ArgumentOutOfRangeException:memberInfo参数必须是针对类FixtureNode,但适用于类FixtureNodeBase。&#34;

带有示例的

LINQPad文件可以从这里下载example.linq

如果您有任何想法,如何解决问题,请分享您的想法。

1 个答案:

答案 0 :(得分:0)

好像,我发现了我的错:

BsonClassMap.RegisterClassMap<FixtureNode>(
  cm =>
  {
    cm.MapMember( x => x.Name );
    cm.MapMember( x => x.Assembly );
    cm.MapMember( x => x.RunnableName );
    cm.MapMember( x => x.Children );
    cm.MapCreator( x => new FixtureNode( x.Name, x.Assembly, x.RunnableName, x.Children ) );
} );

必须更新为

BsonClassMap.RegisterClassMap<FixtureNode>(
  cm =>
  {
    cm.MapMember( x => x.Assembly );
    cm.MapMember( x => x.RunnableName );
    cm.MapCreator( x => new FixtureNode( x.Name, x.Assembly, x.RunnableName, x.Children ) );
} );

即。应该从继承的类映射中删除基类中NameChildren成员的映射。