dotConnect for MongoDB Documentation
On this page
    Entity Framework Core Support
    On this page

    dotConnect for MongoDB supports Entity Framework Core 3.1, 8, 9, 10, and 11. Entity Framework versions 1–6 aren't supported.

    Entity Framework Core Support Key Features

    Using the Entity Data Provider with Entity Framework Core

    To use dotConnect for MongoDB with Entity Framework Core, install the Devart.Data.MongoDB.EFCore NuGet package. The package contains the Devart.Data.MongoDB.EFCore assembly. The provider classes are in the Devart.Data.MongoDB.Entity namespace.

    To register the Entity Framework Core provider and set a connection string, override the OnConfiguring method of your DbContext descendant and call the UseMongoDB method.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) =>
      optionsBuilder.UseMongoDB(
        "Host=localhost;Database=sample;User Id=user;Password=pwd;License Key=***",
        o => o.UseCamelCaseFieldNames());

    The provider works on top of the SQL engine of dotConnect for MongoDB (Sql Engine=true). The Database.ProviderName property of the context returns "Devart.Data.MongoDB.EFCore". To check whether a context uses dotConnect for MongoDB, call the Database.IsMongoDB() method.

    Contexts for multiple databases, for example, a database per tenant, share one internal service provider.

    For step-by-step instructions, see Entity Framework Core Code-First Tutorial and Entity Framework Core Database-First Tutorial.

    Keys

    An entity key is mapped to the _id field of a document. A single string key, such as a key of the ObjectId type in the MongoDB driver, gets an ObjectId generated on insert and is stored as an ObjectId; so are the foreign keys that reference it. To store string keys of your own, configure the key with the ValueGeneratedNever() method. To keep a generated key a string, specify HasColumnType("text"). A Guid key gets its value on the client.

    Field Names

    The names of model properties must match the names of document fields. If the fields are named in camel case, call the UseCamelCaseFieldNames() method in UseMongoDB, as in the example above. Otherwise, specify field names with the HasColumnName method or the [Column] attribute.

    dotConnect for MongoDB also recognizes the following attributes of the official MongoDB driver: BsonId, BsonElement, BsonIgnore, and BsonRepresentation(BsonType.ObjectId).

    Embedded Documents and Arrays

    In Entity Framework Core 8, 9, 10, and 11, OwnsOne maps an embedded document, and OwnsMany maps an array of documents. Entity Framework Core 10 and 11 also support complex properties. With ToJson(null), the properties of an owned type are mapped to the fields of the embedded document one by one, as in Entity Framework Core 3.1; the document stored on the server is the same. The provider adds Json Fields by itself.

    Model fields that don't exist in documents yet are also columns: a query on them returns an empty result.

    In Entity Framework Core 8, 9, 10, and 11, collections of scalars are supported: List<T>, T[], and IList<T> of numbers, strings, dates, decimal, Guid, and enum.

    LINQ queries can filter and project by fields of embedded documents and elements of arrays. You can use Any, All, Contains, Count, Sum, Max, access array elements by index, use SelectMany, and project collections, for example, with Skip and Take.

    // A field of an embedded document
    var fromRome = context.Customers.Where(c => c.Address.City == "Rome").ToList();
    
    // Elements of an array of embedded documents
    var withHomePhone = context.Customers.Where(c => c.Phones.Any(p => p.Kind == "home")).ToList();
    
    // Elements of an array of values
    var vips = context.Customers.Where(c => c.Tags.Contains("vip")).ToList();
    
    // A part of an array in a projection
    var tags = context.Customers.Select(c => new { c.Name, Tags = c.Tags.Skip(1).Take(2) }).ToList();

    When you change one property of an embedded document or an array element, SaveChanges updates only that part of the document.

    In Entity Framework Core 8, 9, 10, and 11, the Scaffold-DbContext command generates owned types for embedded documents and List<T> properties for arrays of values.

    Dates, DateTimeOffset, and Guid Values

    DateTime, DateTimeOffset, and Guid values are stored according to the DateTime Kind, DateTimeOffset Format, and Guid Format connection string parameters. In Entity Framework Core 10 and 11, you can specify a BSON type for a property with the [MongoDBType(MongoDBType.Oid)] attribute or the HasMongoDBType(...) method. For more information, see Entity Framework Core Data Type Mapping.

    Transactions

    On a replica set or a sharded cluster, SaveChanges is executed in a MongoDB transaction. On a standalone server, changes are applied one by one. If the connection string contains Transactions=Required, SaveChanges on a standalone server throws an error.

    Creating Collections

    The EnsureCreated method creates the missing collections of the model with a schema defined by the Schema Validation connection string parameter. It returns true if it creates at least one collection. The EnsureDeleted method deletes the database.

    You can also work with a model collection that doesn't exist yet: queries return an empty result, and SaveChanges inserts documents, so MongoDB creates the collection. This works regardless of the Create Collection On Insert connection string parameter.

    Connection Resiliency

    To retry operations on transient errors, call the EnableRetryOnFailure() method.

    optionsBuilder.UseMongoDB(connectionString, o => o.EnableRetryOnFailure());

    Deploying an Entity Framework Core Project

    When deploying Entity Framework Core projects, make sure that the Devart.Data.dll, Devart.Data.MongoDB.dll, and Devart.Data.MongoDB.EFCore.dll assemblies and the native libraries libmongoc-1.0.dll, libbson-1.0.dll, sqlite3.dll, and vcruntime140.dll (the NuGet package copies them to the output folder) are available for your application. You don't need to register the provider in the machine.config file. For more information, see Deployment.

    Limitations