I have a generic "Create" method. This method will create index by generic type.
public void Create<T>(T node)
{
if (!_elasticClient.IndexExists(_indexName).Exists)
{
var indexSettings = new IndexSettings();
indexSettings.NumberOfReplicas = 1;
indexSettings.NumberOfShards = 3;
var createIndexDescriptor = new CreateIndexDescriptor(_indexName)
.Mappings(ms => ms.Map<T>(m => m.AutoMap()))
.InitializeUsing(new IndexState() { Settings = indexSettings })
.Aliases(a => a.Alias(aliasName));
var response = _elasticClient.CreateIndex(createIndexDescriptor);
}
_elasticClient.Index<T>(node, idx => idx.Index(_indexName));
}
But I getting errors:
The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'MappingsDescriptor.Map(Func<TypeMappingDescriptor, ITypeMapping>)'
The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'ElasticClient.Index(T, Func<IndexDescriptor, IIndexRequest>)'
The .Map<T>()
method in nest uses a class constraint for T
. You need to add the same class constraint to your generic T
.
public void Create<T>(T node)
where T: class
{
// your code here
}