2016-01-21 46 views
0

我將MongoDB文檔映射到C#對象(請參閱this question瞭解一些背景知識),並且一切正常,但是我開始查找一些空的條目。原因是以前的XML只有<VehicleEntry></VehicleEntry>標籤,所以它被作爲'null'插入到BsonDocument的數組中。如何將'null'引用映射到從MongoDB到POCO的默認構造函數?

我可以理解這是預期的行爲,但是當我將它映射到我編寫的VehicleEntry類時,它顯示爲空對象。在我的映射類中,我列出了一堆BsonDefaultValues,甚至添加了一個默認構造函數,但它仍然顯示如果數據庫中的值爲'null',它將創建一個'null'引用對象。

我如何設置它以匹配對所有默認值的對象的空引用?

回答

0

一種解決方案是改變你的LINQ只退回沒有空列表值:

var results = collection.AsQueryable() 
    .Where(v => v.ProjectName.Equals("input") 
    .SelectMan(v => v.VehicleEntries) 
    .Where(i => i != null) 
    .ToList(); 

這並沒有解決其存在的空值的問題,但它提出它被返回任何結果並在顯示數據時避免NPE。

1

如果你創建自己的BsonSerializers並將其分配給VehicleEntry類型,你會那麼可以說,如果該數值爲null,則返回一個default(VehicleEntry)

[TestFixture] 
public class StackQuestionTest 
{ 
    [Test] 
    public void GivenABsonDocumentWithANullForAnPossibleEmbeddedDocument_When_ThenAnInstanceIsSetAsTheEmbeddedDocument() 
    { 
     BsonSerializer.RegisterSerializationProvider(new VehicleEntryBsonSerializationProvider()); 

     var document = new BsonDocument() 
     { 
      {"OtherProperty1", BsonString.Create("12345")}, 
      {"OtherProperty2", BsonString.Create("67890")}, 
      {"VehicleEntry", BsonNull.Value}, 
     }; 

     var rootObject = BsonSerializer.Deserialize<RootObject>(document); 

     Assert.That(rootObject.OtherProperty1, Is.EqualTo("12345")); 
     Assert.That(rootObject.OtherProperty2, Is.EqualTo("67890")); 
     Assert.That(rootObject.VehicleEntry, Is.Not.Null); 
     Assert.That(rootObject.VehicleEntry.What, Is.EqualTo("Magic")); 
    } 
} 

public class VehicleEntrySerializer : BsonClassMapSerializer<VehicleEntry> 
{ 
    public override VehicleEntry Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) 
    { 
     if (context.Reader.GetCurrentBsonType() == BsonType.Null) 
     { 
      context.Reader.ReadNull(); 

      return new VehicleEntry(); 
     } 

     return base.Deserialize(context, args); 
    } 

    public VehicleEntrySerializer(BsonClassMap classMap) : base(classMap) 
    { 

    } 
} 

public class VehicleEntryBsonSerializationProvider : IBsonSerializationProvider 
{ 
    public IBsonSerializer GetSerializer(Type type) 
    { 
     if (type == typeof(VehicleEntry)) 
     { 
      BsonClassMap bsonClassMap = BsonClassMap.LookupClassMap(type); 

      return new VehicleEntrySerializer(bsonClassMap); 
     } 

     return null; 
    } 
} 


public class RootObject 
{ 
    public string OtherProperty1 { get; set; } 

    public string OtherProperty2 { get; set; } 

    public VehicleEntry VehicleEntry { get; set; } 
} 

public class VehicleEntry 
{ 
    public string What { get; set; } = "Magic"; 
} 

http://mongodb.github.io/mongo-csharp-driver/2.0/reference/bson/serialization/

+0

'公共無效GivenABsonDocumentWithANullForAnPossibleEmbeddedDocument_When_ThenAnInstanceIsSetAsTheEmbeddedDocument ()'很好。 – KDecker

+0

'公共無效TestWhatEverIsInQuestion()' –