1

Is there any better way to Write UDTMaps is the same way as Tables using Cassandra Database with C# Driver

Suppose there is a Table called Users(Id, name text, Address frozen )in Cassandra Database. now to map this to C# for Tables I can write as below

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;}
}

Now I can Apply any Configurations with Single Class AppMappings , it can have many mappings with tables. With this one line I can initialize all mappings

MappingConfiguration.Global.Define<AppMappings>();

but inroder to apply UDT I need to add the below line manually.

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

Assume I have 10/20 UDTs then I need to add this line for every UDT. instead is there any way to add UDT Mappings in one place like Mappings? or better approach to add UDT Mappings ?

Akshay Joy
  • 1,765
  • 1
  • 14
  • 23

1 Answers1

3

Unfortunately the driver doesn't have an utility like that one for UDT mappings but you can create something similar like this:

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;
    }
}

Then create your mappings class that contains the udt mappings:

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");
    }
}

And you can use it this way:

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

I think it makes a lot of sense to add something like this to the driver so I created https://datastax-oss.atlassian.net/browse/CSHARP-897 to track this.

João Reis
  • 712
  • 3
  • 9