0

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 "";
    }
3
  • What is the full message of exception? Commented Jul 10, 2019 at 9:55
  • Erreur CS1061 'TEntity' ne contient pas de définition pour 'id' et aucune méthode d'extension accessible 'id' acceptant un premier argument de type 'TEntity' n'a été trouvée (une directive using ou une référence d'assembly est-elle manquante ?) DB Commented Jul 10, 2019 at 10:01
  • Then what type is collection? And does an element of collection have id property inside? Error states that it doesn't Commented Jul 10, 2019 at 10:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.