簡體   English   中英

C# Cassandra UDT 映射配置更好的方法

[英]C# Cassandra UDT Mappings Configuration Better Approach

有沒有更好的方法來編寫 UDTMaps 與使用 Cassandra 數據庫和 C# 驅動程序的表相同

假設 Cassandra 數據庫中有一個名為 Users(Id, name text, Address freeze ) 的表。 現在到 map 這個到 C# 的表格我可以寫如下

public class AppMappings : Mappings
    {
        public AppMappings()
        {
              For<User>()
               .TableName("Users")
               .Column(u => u.Id, cm => cm.WithName("userId"))
               .Column(u => u.Name, cm => cm.WithName("username"))
               .Column(u => u.AddressDetails , cm => cm.WithName("address"))
               .PartitionKey(u=> u.Id);
        }
    }

public class User 
{
   public Guid Id {get;set;}
   public string Name {get;set;}
   public Address AddressDetails {get;set;}
}

public class Address {
   public string State {get;set;}
   public string City {get;set;}
}

現在我可以使用單個 Class AppMappings 應用任何配置,它可以有許多與表的映射。 有了這一行,我可以初始化所有映射

MappingConfiguration.Global.Define<AppMappings>();

但是要應用 UDT 我需要手動添加以下行。

session.UserDefinedTypes.Define(UdtMap.For<Address>("address_udt"));

假設我有 10/20 個 UDT,那么我需要為每個 UDT 添加這一行。 相反,有什么方法可以在一個地方添加 UDT 映射,比如映射? 還是添加 UDT 映射的更好方法?

不幸的是,驅動程序沒有用於 UDT 映射的實用程序,但您可以創建類似的東西:

public abstract class CustomUdtMappings
{
    private readonly IDictionary<Type, UdtMap> _definitions = new Dictionary<Type, UdtMap>();

    public UdtMap[] Definitions => _definitions.Values.ToArray();

    public UdtMap<TPoco> For<TPoco>(string udtName = null, string keyspace = null) where TPoco : new()
    {
        if (_definitions.TryGetValue(typeof(TPoco), out var map) == false)
        {
            map = UdtMap.For<TPoco>(udtName, keyspace);
            _definitions.Add(typeof(TPoco), map);
        }

        return (UdtMap<TPoco>) map;
    }
}

然后創建包含 udt 映射的映射 class:

public class MyAppUdtMappings : CustomUdtMappings
{
    public MyAppUdtMappings()
    {
        For<Udt1>("udt1")
            .Map(udt => udt.Id, "iid")
            .Map(udt => udt.Column1, "aasd");

        For<Udt2>("udt2")
            .Map(udt => udt.Id, "iiid")
            .Map(udt => udt.Column1, "aaasd");
    }
}

你可以這樣使用它:

await session.UserDefinedTypes.DefineAsync(new MyAppUdtMappings().Definitions).ConfigureAwait(false);

我認為向驅動程序添加這樣的東西很有意義,所以我創建了https://datastax-oss.atlassian.net/browse/CSHARP-897來跟蹤它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM