2013-05-06 72 views
2

我使用RavenDB(NoSQL數據庫),我有這個類:存儲空值的實體在某些領域中RavenDB

public class VirtualDirectory 
    { 
     public string Id { get; set; } 
     public string HostAlias { get; set; } 
     public string VirtualPath { get; set; } 
     public string IdentificationMethod { get; set; } 
     public int IsCancelled { get; set; } 
    } 

我通過啓動這個類的一個新實例:

VirtualDirectory vd = new VirtualDirectory() { HostAlias = "bla", IsCancelled = 0 }; 

而且通過保存文件:

using (var session = DbConnection.Instance.DocumentStore.OpenSession(DbName)) 
      { 
       session.Store(vd); 
       session.SaveChanges(); 
      } 

從我所瞭解的NoSQL數據庫文件,該文件是不侷限於模式,所以它們的結構是靈活的。

我的問題是: 如何將數據保存到我的RavenDB數據庫,但沒有在未設置的字段中獲得空值?最後一段代碼後,我的數據庫是這樣的:

{ 
HostAlias : "bla", 
VirtualPath : null, 
IdentificationMethod : null, 
IsCancelled : 0 
} 

當我得到一個C#對象(VirtualDirectory類型),缺少像一些領域:

{ 
HostAlias : "bla", 
IsCancelled : 0 
} 

會是空值?

回答

1

就個人而言,我不確定爲什麼你想要避免在數據庫中的空屬性。

我喜歡使用RavenDb,並具有NULL屬性是完全偉大的,對我有幫助。我相信,如果屬性存在於數據庫中但不在類中(因爲您的類'模式'已更改),那麼它將忽略該數據庫屬性/值。

也就是說,您可以告訴RavenDb在將某些內容保存到數據庫中時該做些什麼。 You can customize the serialization/deserialization process。在這裏,您需要創建自定義ContractResolver

在這種情況下,您需要檢查當前值是否爲空。如果是這樣,你忽略這個屬性。

所以,這是150%未經測試,只是在做一個快速的谷歌搜索後寫在這裏。用它作爲參考。

public class IgnoreNullValuesContractResolver : DefaultRavenContractResolver 
{ 
    public IgnoreNullValuesContractResolver(bool shareCache) 
     : base(shareCache) 
    { 
    } 

    protected override JsonProperty CreateProperty(MemberInfo member, 
                MemberSerialization memberSerialization) 
    { 
     // Grab the property. 
     var property = base.CreateProperty(member, memberSerialization); 

     // Only write this property if the value is NOT null. 
     // NOTE: I have no idea if this is the correct way to retrieve 
     //  the reflected property and it's value. 
     property.Writable = ((PropertyInfo) member).GetValue(member, null) != null; 

     return property; 
    } 
} 

GL :)

0

我相信烏鴉會將你的對象(及其所有屬性)映射到一個Json對象並保存它。因此所有的 你的對象屬性將被保留。

我會做另一個對象 - 那只是我需要的屬性 - 並將其保存到數據庫。

如果您將VirtualDirectory類保存爲raven,您將使用空值將其返回,因爲raven會實例化對象 - 然後填充其具有值的屬性。

這有幫助嗎?

編輯:

下面的評論我做了一個小實驗,發現使用「動態」,你可以很容易地達到你所需要的。 Raven會將其存儲得很好,但它們不會自動聚合到集合中。

這聽起來怎麼樣? :P

+0

爲每個屬性的組合設置對象是沒有意義的。 – ohadinho 2013-05-06 11:39:44

+0

ofc不是 - 我以爲你只是想要你指定的2個屬性作爲你的對象的子集 – JanivZ 2013-05-06 11:48:20

1

使用這ravendb保存:

store.Conventions.CustomizeJsonSerializer =串行=> serializer.NullValueHandling = NullValueHandling.Ignore;

要提取和返回數據:

變種配置= GlobalConfiguration.Configuration;

var settings = config.Formatters.JsonFormatter.SerializerSettings;

settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

+0

工作和測試代碼。 – user3345910 2016-10-11 14:37:37