Can't determine serialization information for i => i.Id using interfaces
First of all, I know there are already questions with this error message, but I haven't found any references to use interfaces with this type of request.
I am currently trying to update MongoDB object with C # Driver 2.0. However, I get an error when I try to create a request (I assume this is a bit of code Builders<T>.Filter.Eq(i => i.Id, entity.Id)
) and I get the following error:
Unable to determine serialization information for i => i.Id.
I have the following class which I am trying to update
public interface IEntity {
string Id { get; set; }
}
public interface ITrack : IEntity {
string Name { get; set; }
}
public class TrackDTO : ITrack
{
[BsonId]
public string Id { get; set; }
public string Name { get; set; }
}
Then I use the interface to store the object in the database using the following method in the general DAO class to replace the entire document. Note that in the example below, T is encoded as ITrack
(i.e. TrackDao = new Dao<ITrack>
), but when an object is passed at runtime, it is an object TrackDTO
(which is correct):
public async Task<T> Save(T entity)
{
// Save the entity to the collection.
ReplaceOneResult result = await _collection.ReplaceOneAsync(Builders<T>.Filter.Eq(i => i.Id, entity.Id), entity, new UpdateOptions() { IsUpsert = true });
// return the saved user object.
return entity;
}
I don't know if the Id property of my class requires an IEntity
attribute [BsonId]
, but I would like to avoid that if possible, since I want to store my model layer (where IEntity
) without any specific reference to the database framework.
I also tried adding the following classmap, which also had no effect:
BsonClassMap.RegisterClassMap<TrackDTO>(cm =>
{
cm.AutoMap();
cm.MapMember(c => c.Id).SetSerializer(new StringSerializer(BsonType.ObjectId));
cm.SetIdMember(cm.GetMemberMap(c => c.Id));
});
For the same reason as the lack of attributes [BsonId]
at the model level, I do not want the decorated Model classes to [BsonKnownTypes]
reference DTO objects, however I do not mind if it is necessary to happen as part of the class map.
source to share
- For
"Unable to determine serialization information for i => i.Id."
Try using: nameof()
.
Builders<T>.Filter.Eq(nameof(IEntity.Id), entity.Id)
2.
... but I would like to avoid this if possible as I want to keep my model (where IEntity is located), without any platform specific referenced database.
My solution to the problem like yours and similar problems:
public interface IEntity {
[BsonId]
string Id { get; set; }
string IdEntity { get; set; }
}
[BsonIgnoreExtraElements(Inherited = true)]
public abstract class BaseEntity : IEntity
{
[BsonRepresentation(BsonType.ObjectId)]
public virtual string Id { get; set; }
[BsonIgnoreIfNull]
public string IdEntity { get; set; }
}
source to share