Sunday, February 28, 2016

Mongo DB With C# API V2

Let's start and check the latest  MongoDb Driver for C# (Mongo V2).

If you are not still configured your Mongo Server yet. see this Post

If you need some guide on old MongoDb Driver V1. See this Post

New Features In V2

  •  Async Support 
  • Method Naming convention with helpful names ( SelectOne, InsertOne etc) 
  • Legacy API Support 

Here is the Db Structure and Sample Data I'm going to Use 

 DB Structure : Create Collection in Mongo Server With name of  Students

















Here is some sample Json Data for Students Collection 

/* 1 */
{
    "_id" : ObjectId("56c3206ddaa3d39f5a130bcc"),
    "StudentId" : 1,
    "Name" : "Saman kumara",
    "Address" : "Sample"
}

/* 2 */
{
    "_id" : ObjectId("56c69ed3926ffb2c80ed00bb"),
    "StudentId" : 2,
    "Name" : "Piyal kumara",
    "Address" : "adadasd"
}


1. Create New MVC Website from Visual Studio

2. Add New Class to the models called Student

public class Student
    {
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { getset; }
        public int StudentId { getset; }
        public string Name { getset; }
        public string Address { getset; }
    }
 
 
 
3. Install MongoCsharpDriver Nuget package from the Nuget
















4. Create ConnetcionString  and Database Variables for mongodb by  R-click on Project -> Properties -> Settings Add relevant values of variables.













5.  Create DbContext Class MongoDbContext 

public class MongoDbContext
    {
        public IMongoDatabase Database;
 
        public MongoDbContext()
        {
            var client = new MongoClient(Settings.Default.ConnectionString);
            Database = client.GetDatabase(Settings.Default.Database);
        }
 
        public IMongoCollection<Student> Students
        {
            get { return Database.GetCollection<Student>("Students"); }
        }
    }


Get data From Mongo

1. Add following code to the HomeController
 Create Private property of Context and initialize it

private MongoDbContext _context { getset; }
 
       public HomeController()
       {
           _context = new MongoDbContext();
       }
       // GET: Home
       public  ActionResult Index()
       {
           //Get Data from Db
           ViewBag.Data = _context.Students.AsQueryable().Select(a=>new Student { Name=a.Name,Address=a.Address ,StudentId=a.StudentId}).ToList();
           return View();
       }

2. Edit The View as following

@{
    ViewBag.Title = "Index";
}
 
<h2>Index</h2>
@Html.ActionLink("Create""Create")
 
 
<table class="table">
    <tr>
        <th>
            Student Id
        </th>
        <th>
            Name
        </th>
        <th>
            Address
        </th>
        <th>
 
        </th>
    </tr>
 
    @foreach (var stu in ViewBag.Data)
    {
        <tr>
            <td>
               @stu.StudentId
            </td>
            <td>
                @stu.Name
                
            </td>
            <td>
               @stu.Address
            </td>
            <td>
                @Html.ActionLink("Edit""Edit"new { id = @stu.StudentId }) | 
                @Html.ActionLink("Delete""Delete"new { id = @stu.StudentId }) 
            </td>
        </tr>
    }
 
</table>


3. Run and see the result ..

Add Documents


Here is sample async code for insert element to the Mongo Context

[HttpPost]
       [ValidateAntiForgeryToken]
       public async Task<ActionResult> Create([Bind(Include = "StudentId,Name,Address")] Student student)
       {
           try
           {
               //Insert one item 
               await _context.Students.InsertOneAsync(student);
               return View();
 
           }
           catch (Exception)
           {
               return View(student);
           }
 
       }
 

Filter Elements

private Student GetStudent(int id)
        {
            //Filter element
            var std = _context.Students
                .Find(r => r.StudentId == id)
                .FirstOrDefault();
            return std;
        }


Update Or Replace Element 

[HttpPost]
       [ValidateAntiForgeryToken]
       public async Task<ActionResult> Edit([Bind(Include = "id,StudentId,Name,Address")] Student student)
       {
           //Full update /replace
           // await _context.Students.ReplaceOneAsync(r => r.StudentId == student.StudentId, student);
          
           //Partial Update
           var update = Builders<Student>.Update.Set(s => s.Name, student.Name);
           await _context.Students.UpdateOneAsync(r => r.StudentId == student.StudentId, update);
           return RedirectToAction("index");
       }


Delete element


public async Task<ActionResult> Delete(int id)
       { 
           //Delete element           
           await _context.Students.DeleteOneAsync(s=> s.StudentId==id);
           return RedirectToAction("index");
       }



Full code In Git ..

https://github.com/prabathsl/DI_Sample


 Enjoy Coding









0 comments: