dotConnect for MongoDB Documentation
On this page
    Entity Framework Core Code-First Tutorial
    On this page

    This tutorial guides you through the process of creating a simple application powered by Entity Framework Core. The application adds a customer with an embedded document and arrays to a MongoDB collection and queries the data.

    Requirements

    This tutorial requires the following:

    The sample code uses embedded documents and arrays, which are supported in Entity Framework Core 8, 9, 10, and 11.

    You don't need to create the customers collection in advance. When SaveChanges inserts the first document, MongoDB creates the collection.

    Creating a New Project

    1. Open Visual Studio.
    2. On the menu bar, select File > New > Project. The Create a new project dialog opens.
    3. Select Console App for C#, then click Next.
    4. Enter the project name and location, then click Next.
    5. Select the target framework, then click Create.

    Installing NuGet Packages

    1. On the menu bar, select Tools > NuGet Package Manager > Package Manager Console.
    2. Run the following command in the Package Manager Console:
      Install-Package Devart.Data.MongoDB.EFCore
      

    Sample Application Code

    1. Add a new Customer.cs file to the project and add the following entity classes to it. The Address property is mapped to an embedded document, the Phones property to an array of embedded documents, and the Tags property to an array of strings.

      using System.Collections.Generic;
      
      public class Customer {
        public string Id { get; set; }
        public string Name { get; set; }
        public Address Address { get; set; }
        public List<Phone> Phones { get; set; }
        public List<string> Tags { get; set; }            // array of values
      }
      
      public class Address {
        public string City { get; set; }
        public string Street { get; set; }
      }
      
      public class Phone {
        public string Kind { get; set; }
        public string Number { get; set; }
      }
    2. Add a new SalesContext.cs file to the project and create a DbContext descendant in it. Override the OnConfiguring method to register the Entity Framework Core provider and specify the connection string, and the OnModelCreating method to configure the mapping.

      using Microsoft.EntityFrameworkCore;
      
      public class SalesContext : DbContext {
        public DbSet<Customer> Customers { get; set; }
      
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) =>
          optionsBuilder.UseMongoDB(
            "Host=localhost;Database=sample;User Id=user;Password=pwd;License Key=***",
            o => o.UseCamelCaseFieldNames());
      
        protected override void OnModelCreating(ModelBuilder modelBuilder) =>
          modelBuilder.Entity<Customer>(e => {
            e.ToTable("customers");
            e.OwnsOne(c => c.Address);                     // embedded document
            e.OwnsMany(c => c.Phones);                     // array of embedded documents
          });
      }

      In this code:

      • UseCamelCaseFieldNames maps the properties to fields in camel case, for example, Name to name.
      • OwnsOne and OwnsMany map the Address and Phones properties to an embedded document and an array of embedded documents, respectively.
    3. Replace the content of the Program.cs file with the following code:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      
      using (var db = new SalesContext()) {
        var customer = new Customer {
          Name = "Eve",
          Address = new Address { City = "Rome", Street = "Via Appia" },
          Phones = new List<Phone> { new Phone { Kind = "home", Number = "123" } },
          Tags = new List<string> { "vip" }
        };
        db.Customers.Add(customer);
        var count = db.SaveChanges();
        Console.WriteLine("{0} records saved to database, new _id: {1}", count, customer.Id);
      
        Console.WriteLine();
        Console.WriteLine("Customers from Rome:");
        foreach (var c in db.Customers.Where(c => c.Address.City == "Rome"))
          Console.WriteLine("{0} | {1}", c.Name, c.Address.Street);
      
        Console.WriteLine();
        Console.WriteLine("Customers with a home phone:");
        foreach (var c in db.Customers.Where(c => c.Phones.Any(p => p.Kind == "home")))
          Console.WriteLine("{0} | {1}", c.Name, c.Phones.First(p => p.Kind == "home").Number);
      
        Console.WriteLine();
        Console.WriteLine("VIP customers:");
        foreach (var c in db.Customers.Where(c => c.Tags.Contains("vip")))
          Console.WriteLine("{0} | {1}", c.Name, string.Join(", ", c.Tags));
      }

      This code inserts a customer document and then selects customers by a field of the embedded document, by an element of the array of documents, and by an element of the array of strings.

    4. On the Debug menu, select Start Without Debugging. The application prints the following:

      1 records saved to database, new _id: 6ae3ab107cb0aece7a2bbc7f
      
      Customers from Rome:
      Eve | Via Appia
      
      Customers with a home phone:
      Eve | 123
      
      VIP customers:
      Eve | vip
      

      The _id of the new customer is different on each run. Each run inserts one more customer, so the next runs print more lines.

    See Also