Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (6.1k points)

There is a need to use a repository pattern that communicates with a MongoDB context for database-level communications.

I have tried to use a very normal interface Entity Framework 4.0 which is as follows. I am facing a problem in finding a member area. Please help me do it with MongoDB context.

public interface IRepository<T> where T : class

{

    void Add(T entity);

    void Remove(T entity);

    IQueryable<T> Find(Expression<Func<T, bool>> predicate);

    //IQueryable<T> FindAll();

}

public class Hero : MongoDB.Kennedy.IMongoEntity

{

    public ObjectId _id { get; set; }

    public string Name { get; set; }

    public string Alias { get; set; }

    public string _accessId { get; set;}

}

public class MongoDataConetext: MongoDB.Kennedy.ConcurrentDataContext

{

    public MongoDataConetext(string databaseName, string serverName="localhost") : base(databaseName, serverName)

    {

    }

    public IQueryable<Hero> Heros {

        get {

            return base.GetCollection<Hero>().AsQueryable();

        }

    }

}

I have added and remove the most simple methods available in my repo, they successfully talk to MongoDB context and get entities added or deleted from MongoDB. But find method gives me compiler level errors. Please help me find the methods. 

public class Repository<T> : IRepository<T> where T : class, IMongoEntity

{

    private readonly MongoDataConetext _ctx;

    public Repository(MongoDataConetext ctx)

    {

        _ctx = ctx;

    }

    public void Add(T entity)

    {

        _ctx.Save(entity);

    }

    public void Remove(T entity)

 {

  _ctx.Delete(entity);

    }

    public IQueryable<T> Find(System.Linq.Expressions.Expression<Func<T, bool>> predicate)

    {

        _ctx.Heros.Where(predicate);

        //throw new NotImplementedException();

    }

    //public IQueryable<T> FindAll()

    //{

    //    throw new NotImplementedException();

    //}

}

1 Answer

0 votes
by (11.7k points)

It seems that LINQ is being used against your collections. This can be done very easily if you just expose an IQueryable property rather than write a Find() method. 

Let’s have a look at the example.

public class HeroRepository : IRepository<Heros> where T : class, IMongoEntity

{

    // ...

    public IQueryable<Heros> Heros 

    {

        get 

        { 

            return _ctx.GetCollection<Heros>().AsQueryable(); 

                  }

    }

}

Just implement it the moment you consume the class.

var r = new HeroRepository();

var heros = r.Heros.Where(r => r.SuperPowerLevel > 20);

Check out this MongoDB tutorial to find more insights into the concepts.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 19, 2021 in SQL by rahulnayar01123 (6.1k points)
0 votes
4 answers
asked Mar 10, 2021 in SQL by rahulnayar01123 (6.1k points)

Browse Categories

...