Coder Social home page Coder Social logo

robthree / mongorepository Goto Github PK

View Code? Open in Web Editor NEW
310.0 42.0 140.0 11.49 MB

Repository abstraction layer on top of Official MongoDB C# driver

Home Page: https://www.nuget.org/packages/MongoRepository/

License: MIT License

C# 99.05% Batchfile 0.05% PowerShell 0.91%
mongodb c-sharp dotnet repository api

mongorepository's Introduction

Logo Project Description

An easy to use library to use MongoDB with .NET. It implements a Repository pattern on top of Official MongoDB C# driver. This project is now available as a NuGet package for your convenience. If you're new to NuGet, check it out; it's painless, easy and fast. You can find this project by searching for MongoRepository in NuGet (or simply clicking here).

Check the documentation for a step-by-step example and more advanced usage.

Example:

// The Entity base-class is provided by MongoRepository
// for all entities you want to use in MongoDb
public class Customer : Entity 
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
}

public class CustomerRepoTest
{
        public void Test()
        {
            var repo = new MongoRepository<Customer>();

            // adding new entity
            var newCustomer = new Customer {
                FirstName = "Steve",
                LastName = "Cornell"
            };

            repo.Add(newCustomer);

            // searching
            var result = repo.Where(c => c.FirstName == "Steve");

            // updating 
            newCustomer.LastName = "Castle";
            repo.Update(newCustomer);
        }
}

Productivity Visual Studio add-in for C#, VB.NET, XML, XAML, ASP.NET and more

mongorepository's People

Contributors

robthree avatar tegeek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongorepository's Issues

mongorepository update specific fields or all fields

var newCustomer = new Customer {
FirstName = "Steve",
LastName = "Cornell"
};
// searching
var result = repo.Where(c => c.FirstName == "Steve");

        // updating 
        newCustomer.LastName = "Castle";
        repo.Update(newCustomer);

in the code above. Update method update one filed lastName or update all fields.
i want to update one field lastname.

Unable to determine the serialization information for the expression

Unable to determine the serialization information for the expression: Enumerable.Select<News, String>(m.MsgBody.news, (News s) => s.title).

I user mongocsharpdriver 1.10.1 .mongodb 3.0 server.
my search code is
var msgList2 = messageRepository.Where(m => m.MsgBody.news.Select(s => s.title).Contains(keyword)).ToList();

collection structure is
26578-20160225224407411-1394691890

data model is

qq 20160226191302

What is the problem? Thanks.

Auth connection string.

Hi Everyone,

I can't run auth connection string. I can connect with any mongodb Gui editor or mongo.exe but Mongorepository always gives error "Command 'authenticate' failed: auth failed (response: { "ok" : 0.0, "errmsg" : "auth failed", "code" : 18 })". My connection string format is "mongodb://user:pass@localhost/DbName",

What is the problem? Thanks.

MongoRepositary with latest MongoDB Driver

We are using MongoRepositary in our project for CRUD operation , Mongo Repository using mongocsharpdriver package. Currently MongoRepository using mongocsharpdriver 1.1.0 version , but latest version of mongocsharpdriver is also available . How I can use MongoRepo with latest MongoDriver or mongocsharpdriver ?

Using the latest MongoDB.Driver ?

Are there any plans to switch to the latest stable MongoDB driver aka 2.3.0? That would be great since I was using the latest version before installing this package and now it replaced the installed versio and some of my code broke.

Datacontext/UnitOfWork

I am new to MongoDB and am trying to get a grip on best practice..
In that past I would have created a Repository, a DataContext maybe a UnitofWork. At first when I looked at your code I thought the DataContext /UnitOfWork abstraction was missing, but thinking about it, the UnitOfWork can be encapsulated by instantiating a repository and performing some action on it. My question would be around latency in creating a connection to MongoDB every time you create a repository. Is there a heavy burden? Do you have any opinion around UnitOfWork etc?

Do not want to use Entity for my classes.

Hi Guys,
I would like to have my application abstracted from data store layer. But in order to use Generic Repository I have to inherit my entities from Entity class. I would like to have no references to your library from my application but inject data layer using container. Do you have any plans to support entities based on DataAnnotation attributes for example, or something else?

How to save enums as strings?

Hi,
I want to ask, how do I force the MongoRepository to save enums to the mongodb as strings, instead of numbers?

Delete method non working on custom class that implements IEntity

Hello, I have defined this baseclass for my objects. I copied it from the Entity class because extending it would mess the collection name mapping mechanism.

  [DataContract]
    [Serializable]
    [BsonIgnoreExtraElements(Inherited = true)]
    public abstract class BaseObject : IEntity<string>
    {
        /// <summary>
        /// Gets or sets the id for this object (the primary record for an entity).
        /// </summary>
        /// <value>The id for this object (the primary record for an entity).</value>
        [DataMember]
        [BsonRepresentation(BsonType.ObjectId)]
        public virtual string Id { get; set; }

        /// <summary>
        /// This method could be invoked to set up somestuff
        /// </summary>
        public virtual void Init() { }

        public virtual DateTime CreationDate
        {
            get { 
                if (!string.IsNullOrWhiteSpace(Id))
                    return ObjectId.Parse(Id).CreationTime;

                return DateTime.MinValue;
            }
        }
    }
}

The problem is that when I call the repository.Delete method nothing happens. I tracked down the code and got to the definition of the method. The problem is in that If statement that only limit the execution to the entity class items while it should be more about who implements the IEntity interface I think.

       /// <summary>
        /// Deletes an entity from the repository by its id.
        /// </summary>
        /// <param name="id">The entity's id.</param>
        public virtual void Delete(TKey id)
        {
            if (typeof(T).IsSubclassOf(typeof(Entity)))
            {
                this.collection.Remove(Query.EQ("_id", new ObjectId(id as string)));
            }
            else
            {
                this.collection.Remove(Query.EQ("_id", BsonValue.Create(id)));
            }
        }

A working solution would be to change it to

 public virtual void Delete(TKey id)
        {
            if (typeof(T).GetInterfaces().Contains(typeof(IEntity<string>)))
            {
                this.collection.Remove(Query.EQ("_id", new ObjectId(id as string)));
            }
            else
            {
                this.collection.Remove(Query.EQ("_id", BsonValue.Create(id)));
            }
        }

Best regards
Marco

Is this package supports MongoDB version 2.2.3?

I updated my MongoDB.Driver to 2.2.3 from a very old version 1.x.x and observed that so many things are broken. Like i cannot see IEntity inteface, ValidateCollectionResult, CollectionStatsResult, GetIndexesResult classes etc.

Delete not working as expected

In version 1.6.8 the Delete function doesn't remove the item. I have to use Collection.Remove(query) for now as a work around.

Certain value types serializing as binary?

So I'm just trying this out for the first time and I noticed that types like Guid and DateTimeOffset were getting serialized as binary blobs and/or byte arrays. Is that normal? I would have thought they would have called ToString() before storing or something.

Support for embedded document update

i have collection like this.

{
  "_id": ObjectId("554e05dfc90d3d4dfcaa2aea"),
  "username": "bodrum",
  "followerList": [
    {
      "_id": ObjectId("554e0625a51586362c33c6df"),
      "follower": "fethiye",
      "avatar": "fethiye.png"
    },
    {
      "_id": ObjectId("554e0625a51586362c33c6df"),
      "follower": "izmir",
      "avatar": "izmir.png"
    }
  ]
} 

I want to remove first follower named as fethiye by follower field.

Version 2

https://github.com/MindMatrix/MongoRepository2

Putting this here in case someone may find it useful, the code was taken from sidecut's https://github.com/sidecut/MongoRepository/tree/v2.4.2 as the base rather than here since it seemed to be the most complete.

  • I implemented .NET Core, .NET Standard and .NET 4.5
  • I implemented the async pattern for all interfaces
  • I removed some ObjectId methods since they defeated the purpose of TKey
  • I removed the manager code from the repository tests and added a separate set of tests for this class
  • I created an InMemoryRepository so that my external project doesn't need to hit the MongoDB during unit tests
  • Collection names for the most part are randomized (except for the few tests that require a specific name). This was needed since the tests run across 3 different .NETs.

MongoServer lifecycle

This is half question, half bug report.

I believe there might be a significant bug in MongoRepository's management of the lifecycle of MongoServer. I believe MongoServer should be singleton/static, and the same instance should be used every time. Otherwise there's some overhead in connecting to the database with each instantiation of the repository.

Here in Util.cs:
private static MongoDatabase GetDatabaseFromUrl(MongoUrl url)
{
var client = new MongoClient(url);
var server = client.GetServer(); // <---- should not be returning a new MongoServer instance!
return server.GetDatabase(url.DatabaseName); // WriteConcern defaulted to Acknowledged
}

See also http://stackoverflow.com/questions/10241641/what-is-the-right-way-to-manage-mongodb-connections-in-asp-net-mvc

I picked this up when looking at performance of queries - was seeing 200ms+ overhead with each new MongoRepository.

Apologies if I have misunderstood the code.

Inner Join or EF Include equivalente

Hi, I'm wondering how to be able to join two or more Repositories result by common properties (normally foreign pks) using this wonderful library. As fas as I know it could be done with EF and SQL but I am very happy with NoSQL.

As MongoRepository seems to implement IQueryable, do you think that something like the next code could work? (if in a fluent way were possible even better^^) thanks!

"from w in repo.Query()
join e in repo.Query() on.."

new mongoCsharpDriver

what about new version of driver?
i've installed the latest version but there is no aversion between two packages

Support for updating individual properties

Hey bud, I've been using MongoRepository for a long time and I LOVE it! It simplifies coding for MongoDB in .NET significantly.

However, there is a fundamental problem with it that greatly hinders scalability. See, the only way you handle updates is by updating the entire document in the database instead of only the properties that have changed. This is extremely wasteful because it uses more bandwidth than necessary to push an entire object, but it also forces the database to re-index the entire collection because the object has been replaced instead of updated.

Do you think this is something you can implement in MongoRepository? I would really appreciate it if you could. Maybe you can have something that tracks changes made to the models, and when "Update()" is called, it will only update the changed properties instead of replacing the entire object.

json serialization issue ASP.Net Web api

When returning an entity object (derived from Entity) from a Web method, only the Id property is retuned; all other properties of the object are ignored in Json format (xml is ok)
I use ASP.Net Web Api Controller Class v2.1
a work araound is to set the [DataMemberAttribute] to each property to export in Json

Support for Multiple Database Names

Not an issue, but more of a feature request.

It would be nice to have an attribute to specify a different database name/ connection string. Currently, the entities will only use the connection string of "MongoServerSettings" If I have 2 collections in different databases, I'm not able to specify this to MongoRepository.

I would like to do something like this:
App.config
<connectionStrings> <add name="MongoServerSettings" connectionString="mongodb://localhost/Application?safe=true" /> <add name="UserDatabase" connectionString="mongodb://localhost/Users?safe=true" /> </connectionStrings>

Then in the Entity file, specify the secondary connectionstring like:
[ConnectionString("UserDatabase")]
public class User : Entity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Username { get; set; }
}
The entity file would by default use "MongoServerSettings" connection string unless the ConnectionString attribute was used.

Separation of interfaces into own assembly

Would be possible to separate the Mongo-independent interface declarations (IRepository, IEntity) into an own assembly (something like Repository.Core) ?
This would allow to use the MongoRepository in client-server scenarios, where the clients would reference just the interface assembly, without having to be aware of the "real" database implementation (Mongo in this case).

Referencing external documents, opposed to embedding.

If I want to store document references instead of embedded documents, how would I best achieve that in the repo? For example, I want to have users that can share newspapers..so something like this, where people can keep references to their favorite newspapers.

class Newspaper:Entity { string Name; string Content; Data publishDate} 
class User:Entity { string LastName; List<Newspaper>newspapers; } 

But internally that List should be serialized to store references to newspapers inside user, not content.

How seamlessly can that be accomplished and should I manually be maintaining those references through in my derived repositories?

Should those references be through ObjectIDs or strings?

Thanks for any help.

Al

how to search mongodb for list of ids

2 example documents of users:

{
"_id": ObjectId("abc"),
"name": "Miroslav",
"tenants": [
"jin"
]
}

{
"_id": ObjectId("abd"),
"name": "Lothar",
"tenants": [
"zhu"
]
}
And I want to fire a single query to Mongo and get the matching documents . like sql server select * from users where id in('abc','abd')
how MongoRepository to do. thank you.

MongoRepository and Aggregation features of MongoDb 3.2 - How to incorporate?

Hello! I have been using MongoRepository for my project and I am keen to understand how best I incorporate the $lookup and $match aggregation features of Mongo 3.2?

I am trying to do this:
private readonly IRepository<UserItem> _userItemRepository; var pipeline = _userItemRepository.Aggregate() .Match(x => x.UserId == userId && x.PublisherId == publisherId);

but unfortunately it does not work (Intellisense errors all over the place) unless I bypass the MongoRepository and go to the MongoClient direct as so:
var client = new MongoClient("mongodb://localhost:27017"); var database = client.GetDatabase("MyDb"); var users = database.GetCollection<UserItem>("users"); var pipeline = users.Aggregate() .Match(x => x.UserId == userId && x.PublisherId == publisherId);

Looking for your advice on how best to approach this?

Create Index

As everyone saying EnsureIndex is obsolete. Can you let me know how can I create an index for a collection? And can i do that at Entity level?

Add new methods to MongoRepository

Hi,

I would like to exetend the standard MongoRepository class.
I try to inherit from MongoRepository<t>.

public class CustomMongoRepository<T> : MongoRepository<T>{}

but it does not work.

Is it possible to do it?

I would like to add some standard methods such as AddOrUpdate(string key) ...

Thanks,

How exactly Update works?

Hi,

I'm working on the update method where i want to update a document basing on the commentID. So, i created a Unique Index on that as below

postcomment.Collection.CreateIndex(new MongoDB.Driver.Builders.IndexKeysBuilder().Ascending("CommentID"), IndexOptions.SetUnique(true));

However when i use update statement for a document it throwing error as below

ERROR WriteConcern detected an error ''. (Response was { "ok" : 1, "code" : 11000, "err" : "E11000 duplicate key error index: SMAnalytics.FacebookComments.$CommentID_1 dup key: { : \"404484049735321_404495519734174\" }", "n" : NumberLong(0) }).

The below is the syntax which i'm using to upate

var cmt = new MComments() { PostID = "56772226", Comment = "Testing", FacebookID = "404484049735321", CommentID = "404484049735321_404495519734174", From = "Bhanu", Comment_Date = Convert.ToDateTime(comment.created_time), Like_Count ="10"}; postcomment.Update(cmt);

Please suggest some solution.. I should update the document If i already have that commentID..

Using a shared MongoClient or MongoDatabase instance

I'm using a MongoDB instance behind self-signed SSL, which means that to use this project I need to include sslVerifyCertificate=false on my connection string... that's bad. ๐Ÿ˜ข

Do you think it would be a good idea to be able to initialise a MongoRepository by passing it a MongoClient. e.g.

var settings = new MongoClientSettings{ /*...*/ }
var client = new MongoClient(settings);
var db = client.GetServer().GetDatabase("mydb");
var repository = new MongoRepository(db, "mycollection");

Also it could be good to have a factory or context that provides the repositories -

var context = new MongoContext(db);
var repository = context.Repository<MyType>("mycollection");

This way you could pass an initialised context around and easily create repositories.

Unable to get individual properties from collection document after inheriting from Entity

The sample class I add earlier was

public class Author:Entity
    {
        public virtual string name { get; set; }
        public string dob  { get; set; }
    }

and the response on getting list of authors was

[
    {
        "id": "5a2983589157cf906c39e808"
    },
    {
        "id": "5a29899fcef3e85b9c427dd9"
    },
    {
        "id": "5a29920fc9ea2c7a38f45085"
    }
]

After adding DataMember to each property like below

public class Author:Entity
    {
        [DataMember]
        public virtual string name { get; set; }
        [DataMember]
        public string dob  { get; set; }
    }

I was able to get the name and dob as part of the response

[
    {
        "name": null,
        "id": "5a2983589157cf906c39e808"
    },
    {
        "name": "Alayo Bolt",
        "id": "5a29899fcef3e85b9c427dd9"
    },
    {
        "name": "Alayo Bolt",
        "id": "5a29920fc9ea2c7a38f45085"
    }
]

Must I add the attribute [DataMember] to every field of my POCO classes before it could map to a field in the container document?

Near queries

How to write near queries using this repository. I need one example that illustrates how to get the near all locations based on latitude and longitude.

and also how to achieve pagination using this repository.

Please help me as soon as possbile

Return only specific fields from repository query?

I have a collection of documents who have a group of simple primitive fields (id, name, status) but also have a very large array on each. As an optimization to reduce query time I would like to only return the light weight document fields when querying the collection, similar to how a "select col1,col2,col3 from tbl" would work in SQL vs the "select * from tbl" I feel that mongo/mongorepository is doing.

Example:
Assume document model { id: 'string', name: 'string', bigarray: [{lots:'data'}]}

For a specific query, I only want to return models with id and name property to save bandwidth and query time by not returning the large payload of the bigarray property. I tried the following, but it feels like it's returning the entire document prior to creating the sparse model.

Repository.SearchFor(c=>c.id=="1234").Select(d=>new model(){ id=d.id, name=d.name}).ToList();

Here's my IRepository SearchFor implementation:

public IQueryable SearchFor(System.Linq.Expressions.Expression<Func<Model, bool>> predicate)
{
return Repository.Where(predicate);
}

Is it possible to return only specific fields from collection documents to create sparse models? I know about BSONIgnore, but that doesn't suit my needs, I need the bigarray property persisted since other queries need to return the full document and rely on that field.

As a longer term fix I'm in the process of refactoring the schema to move the "bigarray" property into it's own collection, and link with a relationship id, but I'm looking for a fix for the interim.

Thanks!

Post data and Entity inherit

Hi,
I have created a model that inherits from Entity. And one that does not inherit from Entity.

The model that inherits from Entity instantiate the object but does not fill the property in the post request. See screenshots.

My model is like this:

public class EmailTransac : Entity
    {   [Required()]
        public string Name { get; set; }
        [Required()]
        public string From { get; set; }
        [Required()]
        public string Template { get; set; }
        [Required()]
        public string Subject { get; set; }
    }

    public class EmailTransacModel
    {
        [Required()]
        public string Name { get; set; }
        [Required()]
        public string From { get; set; }
        [Required()]
        public string Template { get; set; }
        [Required()]
        public string Subject { get; set; }
    }

With inherit of Entity

2015-08-22 17_45_58-gleamr debugging - microsoft visual studio administrator

Without inherit of Entity

2015-08-22 17_47_03-gleamr debugging - microsoft visual studio administrator

My Postman config

2015-08-22 17_47_29-postman

Any ideas how can I fix this?

Thanks,

Unable to write where condition on dates

Hi, I'm unable to write where condition on dates. Whenever I compare the dates it was just hanging. Here is the example

var data = postrepo.Where(x => x.CreatedDate== DateTime.Now);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.