user7709042
user7709042

Reputation:

Update a query in mongoDB with c#

Compiler Error CS1061 in x variable, i want to update a query in mongodb but the problem was throwing an error for x.

public async Task<string> Update(string id, TEntity user)
    {
        await collection.ReplaceOneAsync(x => x.id == id, user);
        return "";
    }

Upvotes: 0

Views: 148

Answers (1)

felix-b
felix-b

Reputation: 8498

In this code: ReplaceOneAsync(x => x.id == id, user) the x is of type TEntity.

The error says that from the compiler point of view, TEntity does not contain property id.

One way to solve it is define an abstraction that every TEntity must inherit from:

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

Then in the repository class (according the method you posted, I assume it is a generic repository class of TEntity), add generic constraint on TEntity as follows:

public class MyRepository<TEntity> where TEntity : IEntity
{
    // collection should be IMongoCollection<TEntity> 
    private IMongoCollection<TEntity> collection; // initialized elsewhere

    public async Task<string> Update(string id, TEntity user)
    {
        await collection.ReplaceOneAsync(x => x.id == id, user);
        return "";
    }

    // ...other members...
}

Since we included generic constraint where TEntity : IEntity, the compiler now knows that every TEntity has a string id property.

Upvotes: 1

Related Questions