- 
                Notifications
    You must be signed in to change notification settings 
- Fork 57
Getting Started
Before working with EFCore-MongoDb, you should first install MongoDb in an environment that is available for testing. MongoDb is free, and supports all major operating systems and CPU architectures. Be sure to install the latest version, as many new features have been added.
CI preview builds can be found on the EFCore-MongoDb feed on MyGet. Once available, release builds will also be posted to NuGet.
To get started with the MyGet feed, add the NuGet package source on your dev machine by executing the follow command from the NuGet Package Manager Console:
nuget sources add -name EFCore-MongoDb -Source https://www.myget.org/gallery/efcore-mongodbNote: this will add a global package source to your dev machine. If you want to limit the source to your current project, add a NuGet.config file to your solution with the following content:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
     <add key="EFCore-MongoDb" value="https://www.myget.org/F/efcore-mongodb/api/v3/index.json" />
  </packageSources>
</configuration>If you are contributing to the code, you should also add the following package sources to ensure that you get the latest EF Core preview builds:
    <add key="AspNetVNext" value="https://www.myget.org/F/aspnetvnext/api/v3/index.json" />
    <add key="NETCore" value="https://dotnet.myget.org/F/dotnet-core/api/v3/index.json" />With the package source in place, you can install the package itself:
Install-Package -IncludePrerelease Blueshift.EntityFrameworkCore.MongoDbThe -IncludePrerelease switch will allow you to stay up-to-date with new features included the project's CI builds.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Blueshift.EntityFrameworkCore.Annotations;
using Microsoft.EntityFrameworkCore;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace Blueshift.EntityFrameworkCore.MongoDb.SampleDomain
{
    [MongoDatabase("zooDb")]
    public class ZooDbContext : DbContext
    {
        public DbSet<Animal> Animals { get; set; }
        public DbSet<Employee> Employees { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMongoDb($"mongodb://localhost");
        }
    }
    [BsonKnownTypes(typeof(Tiger), typeof(PolarBear), typeof(Otter))]
    [BsonDiscriminator(Required = true, RootClass = true)]
    public abstract class Animal
    {
        public ObjectId Id { get; private set; }
        public double Age { get; set; }
        public double Height { get; set; }
        public double Weight { get; set; }
    }
    [BsonDiscriminator("panthera tigris")]
    public class Tiger { }
    [BsonDiscriminator("Ursus maritimus")]
    public class PolarBear { }
    [BsonDiscriminator("Lutrinae")]
    public class Otter { }
    public class Employee
    {
        public ObjectId Id { get; private set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [BsonIgnore]
        public string FullName => string.IsNullOrWhiteSpace(FirstName)
            ? LastName
            : $"{LastName}, {FirstName}";
        public double Age { get; set; }
        public List<Specialty> Specialties { get; set; }
    }
    public enum ZooTask
    {
        Feeding,
        Training,
        Exercise,
        TourGuide
    }
    [ComplexType]
    public class Specialty
    {
        public string AnimalType { get; set; }
        public ZooTask Task { get; set; }
    }
}Note: the OnConfiguring method is one of two ways of specifying which database provider to use with your DbContext. You can also specify the provider while configuring your application's dependency injection:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
namespace Blueshift.EntityFrameworkCore.MongoDb.SampleDomain
{
    public static class ZooDbDependencyInjection
    {
        public static IServiceCollection AddZooDbContext(this IServiceCollection serviceCollection)
        {
            return serviceCollection
                .AddDbContext<ZooDbContext>(options => options.UseMongoDb($"mongodb://localhost"));
        }
    }
}EFCore-MongoDb wraps the MongoDb C# Driver and supports the driver's attributes and conventions. You can use those attributes - such as BsonIdAttribute - and conventions to create your model.
You can now use your model from within your application:
using System;
namespace Blueshift.EntityFrameworkCore.MongoDb.SampleDomain
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new ZooDbContext())
            {
                db.Animals.Add(new Tiger { Name = "Tigger", Age = 6.4, Height = .98, Weight = 201.4 });
                db.SaveChanges();
                foreach (var tiger in db.Animals.OfType<Tiger>())
                {
                    Console.WriteLine($"{tiger.Name}: {tiger.Age}yo, {tiger.Height}m, {tiger.Weight}kg");
                }
                Console.ReadKey();
            }
        }
    }
}