-
Notifications
You must be signed in to change notification settings - Fork 56
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/F/efcore-mongodb/api/v3/index.json
# v2 source: https://www.myget.org/F/efcore-mongodb/api/v2
Note: 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>
While EFCore-MongoDB remains in preview, it will be built against the latest preview builds of .NET Core libraries. In order to get those libraries, you'll need to add the follow package source as well:
<add key="AspNetCore" value="https://dotnet.myget.org/F/aspnetcore-dev/api/v3/index.json" />
NOTE: this package source will also be required if you are contributing to the code, but is already included in the repository's local NuGet.config.
With the package source(s) in place, you can install the package itself:
Install-Package -IncludePrerelease Blueshift.EntityFrameworkCore.MongoDb
The -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;
using System.ComponentModel.DataAnnotations.Schema;
using Blueshift.EntityFrameworkCore.Annotations;
using Microsoft.EntityFrameworkCore;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
namespace Blueshift.EntityFrameworkCore.MongoDB.SampleDomain
{
[MongoDatabase("zooDb")]
public class ZooDbContext : DbContext
{
public DbSet<Animal> Animals { get; set; }
public DbSet<Employee> Employees { get; set; }
public ZooDbContext()
: this(new DbContextOptions<ZooDbContext>())
{
}
public ZooDbContext(DbContextOptions<ZooDbContext> zooDbContextOptions)
: base(zooDbContextOptions)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionString = "mongodb://localhost";
//optionsBuilder.UseMongoDb(connectionString);
var mongoUrl = new MongoUrl(connectionString);
//optionsBuilder.UseMongoDb(mongoUrl);
MongoClientSettings settings = MongoClientSettings.FromUrl(mongoUrl);
//settings.SslSettings = new SslSettings
//{
// EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12
//};
//optionsBuilder.UseMongoDb(settings);
MongoClient mongoClient = new MongoClient(settings);
optionsBuilder.UseMongoDb(mongoClient);
}
}
[BsonKnownTypes(typeof(Tiger), typeof(PolarBear), typeof(Otter))]
[BsonDiscriminator(Required = true, RootClass = true)]
public abstract class Animal
{
[BsonId]
public ObjectId Id { get; private set; }
public string Name { get; set; }
public double Age { get; set; }
public double Height { get; set; }
public double Weight { get; set; }
}
[BsonDiscriminator("panthera tigris")]
public class Tiger : Animal { }
[BsonDiscriminator("Ursus maritimus")]
public class PolarBear : Animal { }
[BsonDiscriminator("Lutrinae")]
[BsonKnownTypes(typeof(SeaOtter), typeof(EurasianOtter))]
public abstract class Otter : Animal { }
[BsonDiscriminator("Enhydra lutris")]
public class SeaOtter : Otter { }
[BsonDiscriminator("Lutra lutra")]
public class EurasianOtter : Otter { }
public class Employee
{
[Key]
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; } = new List<Specialty>();
}
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();
}
}
}
}