是否可以在 NEST6 中将枚举存储为字符串?
我已经试过了,但似乎不起作用。有什么建议吗?
var pool = new SingleNodeConnectionPool(new Uri(context.ConnectionString));
connectionSettings = new ConnectionSettings(pool, connection, SourceSerializer());
private static ConnectionSettings.SourceSerializerFactory SourceSerializer()
{
return (builtin, settings) => new JsonNetSerializer(builtin, settings,
() => new JsonSerializerSettings
{
Converters = new List<JsonConverter>
{
new StringEnumConverter()
}
});
}
最佳答案
使用 StringEnumAttribute
attribute在属性(property)上。这向内部序列化器发出信号,将枚举序列化为字符串。在使用它时,您不需要使用 NEST.JsonNetSerializer package
如果你想为所有枚举设置它,你可以这样做
private static void Main()
{
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var connectionSettings = new ConnectionSettings(
pool,
(builtin, settings) => new JsonNetSerializer(builtin, settings,
contractJsonConverters: new JsonConverter[] { new StringEnumConverter() }));
var client = new ElasticClient(connectionSettings);
client.Index(new Product { Foo = Foo.Bar }, i => i.Index("examples"));
}
public class Product
{
public Foo Foo { get;set; }
}
public enum Foo
{
Bar
}
这会产生一个像
这样的请求POST http://localhost:9200/examples/product
{
"foo": "Bar"
}
我认为您尝试设置转换器的方式也应该有效,并且是一个错误,但它没有。我将打开一个问题来解决。
关于Elasticsearch/NEST 6 - 将枚举存储为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49224866/