I'm trying to make a selection on the Type
field, CloudFileTypes
is an enum
. If you try to make a selection using linq methods or mongodb driver filter, then it perceives Type
as a number and cannot find the desired file, and in the database in the Type
field I have string
values. And if I select some specific file and access the type field, then it will return the enumeration member, as needed.
I apologize in advance if I misunderstood.
Problem part of code:
public CloudFile GetRoot(User user)
{
var builder = Builders<CloudFile>.Filter;
var query = builder.Eq(e => e.Type, CloudFileTypes.Root);
var root = _fileCollection.Find(query).First();
return root.First();
}
CloudFile
model:
public class CloudFile
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("name")] public string Name { get; set; }
[JsonConverter(typeof(JsonStringEnumConverter))]
[BsonElement("type")] public CloudFileTypes Type { get; set; }
[BsonElement("size")] public int Size { get; set; }
[BsonElement("path")] public string Path { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
[BsonElement("user")] public string User { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
[BsonElement("parent")] public string Parent { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
[BsonElement("childs")] public string[] Childs { get; set; }
}
public enum CloudFileTypes
{
[EnumMember(Value = "root")] Root,
[EnumMember(Value = "folder")] Folder,
[EnumMember(Value = "file")] File,
}
How do i solve this problem. Tried googling, didn't work.
EDIT: JsonConverter I created to serialize the enum
when the object is sent to the client, using the extension from Yong Shun:
public class EnumStringConverter<TEnum> : JsonConverter where TEnum: struct, Enum
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(CloudFileTypes);
}
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value is not TEnum @enum)
return;
if (!Attribute.IsDefined(@enum.GetType().GetMember(@enum.ToString()).FirstOrDefault(), typeof(EnumMemberAttribute)))
writer.WriteValue(@enum.ToString());
writer.WriteValue(EnumExtensions.GetEnumMemberValue(@enum));
}
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
var str = jo.ToString();
var obj = EnumExtensions.EnumMemberValueToEnum<CloudFileTypes>(str);
return obj;
}
}