4

I am using the C# driver 2.0. I have a POCO that I am storing in mongo that looks like this:

public class TestObject
{
     [BsonId]
     public Guid Id { get; set; }
     public string Property1 { get; set; }
}

I am storing the object using a generic method like this:

public async void Insert<T>(T item)
{
        var collection = GetCollection<T>();

        await collection.InsertOneAsync(item);
}

I would like to have a similar method to Update an object. However, the ReplaceOneAsync method requires a filter be specified.

I would like to simply update the same object, based on whatever the [BsonId] property is. Any one know if this is possible?

BigJoe714
  • 6,732
  • 7
  • 46
  • 50
  • You need a filter with the id. Otherwise you will update all the documents. – i3arnon Jun 12 '15 at 12:43
  • But since I am trying to create a generic method to do the update for me, i don't know which field is the ID field on the object. – BigJoe714 Jun 12 '15 at 12:47
  • 1
    you can add an interface that only has an ID and accept that. Or use reflection to see what has BsonId. But you need an Id for the filter – i3arnon Jun 12 '15 at 12:49

1 Answers1

7

I completely agree with @i3arnon, typical solution is next:

interface for your models:

public interface IEntity
{
    string Id { get; set; }
}

save method in your base repository

public async Task SaveAsyn<T>(T entity) where T : IEntity
{
    var collection = GetCollection<T>();
    if (entity.Id == null)
    {
        await collection.InsertOneAsync(entity);
    }
    else
    {
        await collection.ReplaceOneAsync(x => x.Id == entity.Id, entity);
    }
}

And also about ID, you can continue using ID as Guid, but more robust and simpler solution is using string (explanation about Id).

Community
  • 1
  • 1
rnofenko
  • 9,198
  • 2
  • 46
  • 56