Coder Social home page Coder Social logo

blueshiftsoftware / entityframeworkcore Goto Github PK

View Code? Open in Web Editor NEW
282.0 35.0 58.0 547 KB

NoSQL providers for EntityFramework Core

License: Other

Batchfile 0.07% PowerShell 0.98% Shell 1.27% C# 97.68% Smalltalk 0.01%
entityframeworkcore mongodb dotnet dotnet-core

entityframeworkcore's Introduction

Document Database Providers for Entity Framework Core

Welcome to the home of Document Database (NoSQL) Providers for EntityFrameworkCore!

AppVeyor Build Status Travis CI Build Status

This repository currently only contains a MongoDB provider for EF Core. However, there are plans in the current roadmap to expand this with further NoSQL provider offerings.

MongoDb is a highly popular No-SQL database solution for storing structured, non-relational document data. This provider enables applications built with EntityFrameworkCore to use MongoDb instances as a backing data store.

Find out how to get started by visiting the Wiki pages. Feel free to contribute to this repository with code, comments, wiki entries, and/or issues.

The latest release and CI previews builds are available at the EntityFrameworkCore.MongoDb MyGet Feed.

entityframeworkcore's People

Contributors

crhairr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

entityframeworkcore's Issues

Self refrence read not support

public class Area
{
///


/// Id
///

[BsonId]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public ObjectId Id { get; private set; }

    public string Name { get; set; }
 
    public string Code { get; set; }
          
    public virtual Area Parent { get; set; }

    //[ForeignKey("Id")]
    
    public virtual ICollection<Area> Areas { get; set; }
}

Save success ,but can not read from mongo

Multiple DbCntexts select query can't work concurrently.

Multiple DbContexts select query can't work concurrently. Please see the code below.
BTW, if I use async query, "System.ObjectDisposedException : Cannot access a disposed object." will occur.
`

    public async Task ConcurrentTest()
    {
        var tasks = new List<Task>();
        for (int i = 0; i < 20; i++)
        {
            var j = i;
            tasks.Add(Task.Run(() => InternalGetUsersTest(j)));
        }
        await Task.WhenAll(tasks);
    }

    private void InternalGetUsersTest(int i)
    {
        var builder = new DbContextOptionsBuilder().UseMongoDb("mongodb://10.100.7.46:9007/DemoDb");
        using (var dbContext = new DemoDbContext(builder.Options))
        {
            var database = dbContext.GetMongoDbDatabase();
            // !!! 20 concurrent tasks cost 3 seconds.
            var user1 = database.GetCollection<User>("users")
                                .Find(new ExpressionFilterDefinition<User>(u => u.Id == "xxx"));

            // !!! 20 concurrent tasks cost almost 20 seconds. It seems each task run one by one.
            var user2 = dbContext.Users
                                 .FirstOrDefault(u => u.Id == "xxx");
        }
    }`

InvalidOperationException when using ObjectId in an action

In the same project attached in the previous issue, this works fine (using string as a parameter):

OwnerController

public class OwnerController : Controller
{
    public async Task<IActionResult> Add(string id)
    {
        //var objectId = new ObjectId(id); // this is the workaround way
    }
}

But when I change it into this:

public async Task<IActionResult> Add(ObjectId id)

It causes this exception:

InvalidOperationException: Could not create an instance of type 'MongoDB.Bson.ObjectId'. Model bound complex types must not be abstract or value types and must have a parameterless constructor.

The weird part is that in the CarsController, this works fine:

public async Task<IActionResult> Edit(ObjectId id)
{
    var car = await _context.Car.SingleOrDefaultAsync(m => m.Id == id);
    if (car == null)
    {
        return NotFound();
    }
    return View(car);
}

Updating a Child "Document" inside array

I am wondering how I would go about updating an child instance in an array?

Here are my models

public class Recording
{
	[BsonId]
	[Key]
	[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
	public ObjectId Id { get; set; }
		
	//Other Properties

	public List<VideoFragment> VideoFragments { get; set; } = new List<VideoFragment>();
}
[ComplexType]
public class VideoFragment
{
	public string Url { get; set; }
	public byte[] Data { get; set; }
}

Here is my Context

public class MyDbContext : DbContext
{
	public StreamcorderDbContext(DbContextOptions options) : base(options)
	{ }

	public DbSet<Recording> Recordings { get; set; }
}

I am wanting to update an existing Video Fragment by looking it up by Url then saving a byte array of data
Here is what I currently have:

public void SaveFragmentData(ObjectId recordingId, string fragmentUrl, byte[] data)
{
	var recording = _db.Recordings.Single(r => r.Id == recordingId);
	var fragment = recording.VideoFragments.Single(f=> f.Url == fragmentUrl);
	fragment.Data = data;
	_db.Recordings.Update(recording);
	_db.SaveChanges();
}

I add get the recording, update the specific fragment of the recording then save it.

I was hoping there might be a way to just get the fragment and update it individually.

Here is a copy of my document:

{
  "_id": "5b5099d4139c5907ccddeac3",
  "VideoFragments": [
    {
      "Url": "http://video-edge-85675c.syd01.abs.hls.ttvnw.net/v1/segment/CqEDdEsv7E8bCOEbkLIhBFQSmJ8XZv2-_1G....ts",
      "Data": "<Binary Data>"
    },
    {
      "Url": "http://video-edge-85675c.syd01.abs.hls.ttvnw.net/v1/segment/CqED-2SjHzRiHw4Vx9aIaGm8YrO2IVICuhK....ts",
      "Data": "<Binary Data>"
    },
    {
      "Url": "http://video-edge-85675c.syd01.abs.hls.ttvnw.net/v1/segment/CqEDj_wly9Rd0ZviOtA70UkzqGJHAE8jgZA....ts",
      "Data": null
    },
    {
      "Url": "http://video-edge-85675c.syd01.abs.hls.ttvnw.net/v1/segment/CqED5gZajJanx0rSVEt7tWTcr0s_hPBbMML....ts",
      "Data": null
    },
    {
      "Url": "http://video-edge-85675c.syd01.abs.hls.ttvnw.net/v1/segment/CqED4FZm9CfX5NVYVSYGhwbCpzW4nOTObmP....ts",
      "Data": "<Binary Data>"
    }
  ]
}

Could you help me out?

Ps thanks for creating a provider like this, its super helpful to try out.

Does this work with IdentityServer4 ?

Great library,
We are investigating using IdentityServer4 for authentication and currently all MongoDb versions are not working well.
My question, have you tried using your library (with Identity support) in any production solutions like IdentityServer4?
P.S: I'll give it a try

NullReferenceException with OO models

Hi,

While I was trying to see if mongo can fit my future projects, I landed to this provider... great work guys!

This issue is with version:

2.0.0-preview-t004f07459
.net core 2.0 project template made with vs 2017

Well, the ToListAsync causes an exception when there is a nested object, as in here:

public class Car
{
    public Car()
    {
        Owner = new Owner{Id = ObjectId.GenerateNewId()};
    }
    [BsonId]
    public ObjectId Id { get; set; }
    public string Model { get; set; }
    public int Price { get; set; }
    public Owner Owner { get; set; }
}

public class Owner
{
    public Owner()
    {
    	Name = "";
    }
    [BsonId]
    public ObjectId Id { get; set; }
    public string Name { get; set; }
}

But listing works fine when I have such a model (no nested documents):

public class Car
{
    [BsonId]
    public ObjectId Id { get; set; }
    public string Model { get; set; }
    public int Price { get; set; }
}

Controller action is ordinary:

// GET: Cars
public async Task<IActionResult> Index()
{
    var cars = await _context.Car.ToListAsync();
    
    return View(cars);
}

Method ".Ignore(string propertyName)" (*Fluent api)

Hi, I am working now with some third party legacy POCOs classes where I had to remove some properties from the mapping, but the Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder.Ignore(string propertyName) implementation, seems not to be working.
I have been able to workaround it using BsonClassMap.RegisterClassMap(cm => cm.UnmapMember(MemberInfo)) on the context's onModelCreating but I am afraid of problems that this might lead. Is there some mongodb design limitation or is it possible to implement it, Chris?

DbSet of an interface type

When adding a dbset like this:

public DbSet<IOwner> Owners { get; set; }

This exception occurs:

ArgumentException: The entity type 'EFMongoDemo.Web.Models.IOwner' provided for the argument 'clrType' must be a reference type.
Microsoft.EntityFrameworkCore.Utilities.Check.ValidEntityType(Type value, string parameterName)

I know that using a base type is a solution, but it would just much better for scaling apps to use interfaces (not sure if possible).

Get ObjectDisposedException when execute same query on differend DbContext instances

Hello.
I always get ObjectDisposedException when execute same query on differend instances of dbContext. Firs execution is succesfull but second execution on different instance of dbContext fails with ObjectDisposedException:
System.ObjectDisposedException : Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.

Here the test case to reproduse this issue:

        [Fact]
        public async Task Can_execute_same_async_query_from_different_dbContext_instances()
        {
            await ExecuteUnitOfWorkAsync(async zooDbContext =>
            {
                zooDbContext.Animals.AddRange(_zooEntities.Animals);
                Assert.Equal(
                    _zooEntities.Entities.Count,
                    await zooDbContext.SaveChangesAsync(acceptAllChangesOnSuccess: true));
            });

            Func<ZooDbContext, Task<List<Animal>>> query = (zooDbContext) => 
            zooDbContext.Animals
                .OrderBy(animal => animal.Name)
                .ThenBy(animal => animal.Height)
                .ToListAsync();

            await ExecuteUnitOfWorkAsync(async zooDbContext =>
            {
                Assert.Equal(_zooEntities.Animals,
                    await query.Invoke(zooDbContext),
                    new AnimalEqualityComparer());
            });

            await ExecuteUnitOfWorkAsync(async zooDbContext =>
            {
                Assert.Equal(_zooEntities.Animals,
                    await query.Invoke(zooDbContext),
                    new AnimalEqualityComparer());
            });
        }

The problem seems to be in last changes of `MongoDbDatabase.CompileAsyncQuery()' method:

public override Func<QueryContext, IAsyncEnumerable<TResult>> CompileAsyncQuery<TResult>(QueryModel queryModel)
            => queryContext => CompileQuery<TResult>(queryModel)(queryContext).ToAsyncEnumerable();

I think the problem in above code is CompileQuery<TResult>(queryModel) executes within lambda and queryModel have been disposed some way on second query execution.

When I revert previous version of this method iisue disappears:

 public override Func<QueryContext, IAsyncEnumerable<TResult>> CompileAsyncQuery<TResult>(QueryModel queryModel)
        {
            var syncQueryExecutor = CompileQuery<TResult>(queryModel);
            return qc => syncQueryExecutor(qc).ToAsyncEnumerable();
        }

related to this comment in another issue:
#29 (comment)

Roadmap

Is there a roadmap available?

Hangs on UseMongoDb

I created a database named EFCoreTest and added the following user

db.createUser(
   {
     user: "x",
     pwd: passwordPrompt(),  // or cleartext password
     roles: [
        { role: "readWrite", db: "EFCoreTest" }
     ]
   }
 );

But my Console app freezes as soon as the UseMongoDb command is executed.

			var builder = new DbContextOptionsBuilder<AppDbContext>();
			var mongoUrl = new MongoUrlBuilder()
			{
				Server = new MongoServerAddress("127.0.0.1"),
				DatabaseName = "EFCoreTest",
				Username = "x",
				Password = "x"
			}.ToMongoUrl();
			builder.UseMongoDb(mongoUrl);

This is using Blueshift.EntityFrameworkCore.MongoDB-aleksamagicka 2.2.0-rtm-1 with EntityFrameworkCore 3.1.6 in a .NET Core 3.1 console app.

Do you have any suggestions?

Add support for mongoDb database name info passed on connection string/url

A nice feature would be using the database name information passed on the connection string/url (and be able to change dynamically on the context method, OnModelCreating - like on sql server), instead using the MongoDatabase Attribute. I have been working on a project involving ETL and tried achieve that by some other way but no success. There is any workaround on the actual source?

MissingMethodException: Method not found: 'Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(System.Type, Microsoft.EntityFrameworkCore.Metadata.Internal.ConfigurationSource)'

Hello, i have this issues: "MissingMethodException"

exception as follows:

An unhandled exception occurred while processing the request.

MissingMethodException: Method not found: 'Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(System.Type, Microsoft.EntityFrameworkCore.Metadata.Internal.ConfigurationSource)'.
Blueshift.EntityFrameworkCore.MongoDB.Metadata.Conventions.MongoDbRegisterKnownTypesConvention.Apply(InternalEntityTypeBuilder entityTypeBuilder)

############################################################
MissingMethodException: Method not found: 'Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(System.Type, Microsoft.EntityFrameworkCore.Metadata.Internal.ConfigurationSource)'.
Blueshift.EntityFrameworkCore.MongoDB.Metadata.Conventions.MongoDbRegisterKnownTypesConvention.Apply(InternalEntityTypeBuilder entityTypeBuilder)
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher+ImmediateConventionScope.OnEntityTypeAdded(InternalEntityTypeBuilder entityTypeBuilder)
Microsoft.EntityFrameworkCore.Metadata.Internal.Model.AddEntityType(EntityType entityType)
Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(TypeIdentity type, ConfigurationSource configurationSource, bool throwOnQuery)
Microsoft.EntityFrameworkCore.ModelBuilder.Entity(Type type)
Microsoft.EntityFrameworkCore.Infrastructure.ModelCustomizer.FindSets(ModelBuilder modelBuilder, DbContext context)
Microsoft.EntityFrameworkCore.Infrastructure.ModelCustomizer.Customize(ModelBuilder modelBuilder, DbContext context)
Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
System.Collections.Concurrent.ConcurrentDictionary.GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
lambda_method(Closure , ServiceProviderEngineScope )
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider)
Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
Microsoft.EntityFrameworkCore.DbContext.get_Model()
Microsoft.EntityFrameworkCore.Internal.InternalDbSet.get_EntityType()
Microsoft.EntityFrameworkCore.Internal.InternalDbSet.get_EntityQueryable()
Microsoft.EntityFrameworkCore.Internal.InternalDbSet.System.Collections.Generic.IEnumerable.GetEnumerator()
System.Collections.Generic.List.AddEnumerable(IEnumerable enumerable)
System.Linq.Enumerable.ToList(IEnumerable source)
Amazing.Api.Controllers.BlogsController.GetBlogs(ODataQueryOptions queryOptions) in BlogsController.cs
+
var result = db.blogs.ToList();
lambda_method(Closure , object , Object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, Object[] parameters)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d__12.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d__10.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+d__14.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__22.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__17.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__15.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()
##########################################################################
Show raw exception details
System.MissingMethodException: Method not found: 'Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(System.Type, Microsoft.EntityFrameworkCore.Metadata.Internal.ConfigurationSource)'.
at Blueshift.EntityFrameworkCore.MongoDB.Metadata.Conventions.MongoDbRegisterKnownTypesConvention.Apply(InternalEntityTypeBuilder entityTypeBuilder)
at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnEntityTypeAdded(InternalEntityTypeBuilder entityTypeBuilder)
at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.AddEntityType(EntityType entityType)
at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(TypeIdentity type, ConfigurationSource configurationSource, Boolean throwOnQuery)
at Microsoft.EntityFrameworkCore.ModelBuilder.Entity(Type type)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelCustomizer.FindSets(ModelBuilder modelBuilder, DbContext context)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelCustomizer.Customize(ModelBuilder modelBuilder, DbContext context)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
at lambda_method(Closure , ServiceProviderEngineScope )
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.get_Model()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.get_EntityType() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.get_EntityQueryable()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet1.System.Collections.Generic.IEnumerable<TEntity>.GetEnumerator() at System.Collections.Generic.List1.AddEnumerable(IEnumerable1 enumerable) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source)
at Amazing.Api.Controllers.BlogsController.GetBlogs(ODataQueryOptions`1 queryOptions) in /Users/yangxiaoming/Amazing.vNext/Amazing.Api/Controllers/BlogsController.cs:line 35
at lambda_method(Closure , Object , Object[] )
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.d__7.MoveNext()

###########################################################################
How to solve it? Thanks.

dbContext.DBSet.FirstOrDefault(e => e.FirstName == "xx") missing filter in MongoQueryable

zooDbContext.Employees .FirstOrDefault(e => e.FirstName == "xx") will retrieve all records from employees collection in mongodb.

Reproduce step:

  1. Open mongo shell and use the command "db.setProfilingLevel(2)" to open the query profiler.
  2. Execute zooDbContext.Employees .FirstOrDefault(e => e.FirstName == "xx") in test case.
  3. Use db.system.profile.find().sort({$natural:-1}) to view the profiler data.
    From the profiler data, we can see there is no filter or pipeline in the command.

`

{
"op" : "command",
"ns" : "zooDb.employees",
"command" : {
    "aggregate" : "employees",
    "pipeline" : [],
    "cursor" : {},
    "$db" : "zooDb",
    "lsid" : {
        "id" : UUID("5854cdca-ee1e-44d2-8098-5d1ae3ed06a3")
    }
},
"keysExamined" : 0,
"docsExamined" : 2,
"cursorExhausted" : true,
"numYield" : 0,
"locks" : {
    "Global" : {
        "acquireCount" : {
            "r" : NumberLong(4)
        }
    },
    "Database" : {
        "acquireCount" : {
            "r" : NumberLong(2)
        }
    },
    "Collection" : {
        "acquireCount" : {
            "r" : NumberLong(2)
        }
    }
},
"nreturned" : 2,
"responseLength" : 422,
"protocol" : "op_msg",
"millis" : 0,
"planSummary" : "COLLSCAN",
"ts" : ISODate("2018-12-11T09:05:25.129Z"),
"client" : "127.0.0.1",
"allUsers" : [],
"user" : ""

}

`

Unable to install the package

Installing the latest preview (21.04.17) leads to compilation errors in my solution.

I'm using .net standard library 1.6 and EF 1.0.0

InvalidOperationException when adding derived to a base-type dbset

Hi,

I added many many stuff into the demo repo:
https://github.com/0xRumple/EFMongoDemo

I started using a base class for the owners (Employee and Manager) which is called Owner instead of the IOwner interface when talking to the database cuz as you the EF core doesn't support that even in In-Memory unit tests 😞 .

In the dbsets, I used:

public DbSet<Owner> Owners { get; set; }

But this doesn't even create a collection in the db when I add an owner, instead it just causes an exception:

InvalidOperationException: The entity type 'Employee' was not found. Ensure that the entity type has been added to the model.

I also tried specifiying which to dbset to add to by overriding the adding behavior in the OwnerRepository but same result:

public override async Task<Owner> Add(Owner entity)
    {
        Context.Owners.Add(entity);
        await CommitChanges();
        
        return entity;
    }

For testing, the EFMongoDemo.Tests.DataTests.CarRepositoryShould.GetById_JoinCarAndOwner shows the same result.

*P.S:
Using this will be fine:

public DbSet<Employee> Owners { get; set; }

*P.P.S:
In mssql provider if I use the base type, it will annoyingly map all the properties in both derived types, in this case both AllowedNumberToOwn and AffliatedEmployees will be mapped into one table called "Owners" to satisfy the EF.

InvalidOperationException when using an entity without an Id

Hi again,

I'm using a view model to update the owner data:

public class OwnerUpdateViewModel
{
    public SelectList OwnerType { get; set; }
    public string OwnerName { get; set; }
    
    public IOwner ToModel()
    {
        var result = OwnerHelper.GetOwner(OwnerType.SelectedValue.ToString());
        result.Name = OwnerName;
        
        return result;
    }
}

Get action:

public async Task<IActionResult> Update(ObjectId id)
{
    var car = await _context.Cars.SingleOrDefaultAsync(m => m.Id == id);
    if (car == null)
    {
       return NotFound("Invalid car id!");
    }
    
    return View();
}

It will throw an exception:

InvalidOperationException: The entity type 'OwnerUpdateViewModel' requires a primary key to be defined.

Only with this it will work is to add this property to the view model:

public ObjectId Id { get; set; }

(as you know, the usage of the view model is to eliminate the Id and show only the needed stuff)

*P.S:
I realized the best way to figure out the issues of EFMongo library is to make a "semi" real-life-project.
I started organizing things in that project, I'm gonna push it into github; it'll also serve as a good example for new comers.

Navigating to a foreign document doesn't load any of it's data, only the Id field is populated

Hey, when I navigate to a document via a virtual property I would normally expect EF to lazy load the entity (with everything populated). When I try this with MongoDb it returns an empty entity with just the Id field populated.

I would have thought it should load the entire document to avoid having to write an additional query every time I want to fetch the data. In my mind that's the whole point of the virtual property (otherwise I'd just store the Id field).

Thoughts? Am I doing it wrong?
Cheers.

Example:

public class AccountData
{
    public Guid Id { get; set; }
    public string Username { get; set; } = string.Empty;
    public ICollection<UserItem> EmbededList { get; set; }
}

public class UserItem
{
    public string Name { get; set; }
    public int Foo { get; set; }
    public bool Bar { get; set; }
}

public class CharacterData
{
    public Guid Id { get; set; }
    public string Name { get; set; }

    // Navigation to account document
    public virtual AccountData Account { get; set; }
}

static void Main(string[] args)
{
`Console.WriteLine("Running...");
    try
    {
        using (var context = new FooContext())
        {
            var account = context.Accounts.Add(new AccountData()
            {
                Username = "acc" + new Random().Next(Int32.MaxValue),
                EmbededList = new List<UserItem>()
                {
                    new UserItem() {Name = "asd", Bar = true, Foo = 1001},
                    new UserItem() {Name = "asd2", Bar = false, Foo = 1002},
                    new UserItem() {Name = "asd3", Bar = true, Foo = 1003},
                }
            });

            context.Characters.Add(new CharacterData()
            {
                Name = "char" + new Random().Next(Int32.MaxValue),
                Account = account.Entity,
            });

            context.SaveChanges();

            // Document created as expected with _id for the Account document created.
            /*
            AccountData:
            {
                "_id" : LUUID("5331bdd2-ad9e-b547-acb0-b6eeec3253d9"),
                "Username" : "acc1796538846",
                "EmbeddedList" : [ 
                    {
                        "Name" : "asd",
                        "Foo" : 1001,
                        "Bar" : true
                    }, 
                    {
                        "Name" : "asd2",
                        "Foo" : 1002,
                        "Bar" : false
                    }, 
                    {
                        "Name" : "asd3",
                        "Foo" : 1003,
                        "Bar" : true
                    }
                ]
            }

        CharacterData:
            {
                "_id" : LUUID("b2a803f3-afbe-8145-b11e-38e1f4362ea0"),
                "Name" : "char1363200943",
                "Account" : {
                    "_id" : LUUID("5331bdd2-ad9e-b547-acb0-b6eeec3253d9")
                }
            }
                */

        }
                
        // Now trying to navigate to the AccountData from the CharacterData entity.
        using (var context = new FooContext())
        {
            var character = context.Characters.First();
            var account = character.Account;
            Console.WriteLine($"Test: {account.Id}");           // CORRECT (Guid)
            Console.WriteLine($"Test: {account.Username}");     // WRONG (Blank username)
            Console.WriteLine($"Test: {account.EmbededList}");  // WRONG (Empty list)
        }

    }
    catch (Exception ex)
    {
        throw ex;
    }

    Console.WriteLine("done!");
    Console.ReadLine();
}

Add support for registered classes in BsonClassMap

Would be interesting look into BsonClassMap and get mapping informations instead of using Attribute, because many times we have isolated entities/pocos in determined project and can't add references for one or more technology.

Other problem is: sometimes we make routines thats use reflections to generate map dynamiclly on BsonClassMap.

What you think about this?

bug: can not modify child

[MongoDatabase("fengpintech")]
public class MongoContext : DbContext
{
public DbSet Customers { get; set; }

    public MongoContext()
       : this(new DbContextOptions<MongoContext>())
    {

    }
 
    public MongoContext(DbContextOptions<MongoContext> dataCenterContextOptions)
       : base(dataCenterContextOptions)
    {

    }       
}

public class Customer
{
///


/// Key
///

[BsonId]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public ObjectId Id { get; private set; }

    public string EnterpriseName { get; set; }

    public List<Aptitude> Aptitudes { get; set; } = new List<Aptitude>();
}

[ComplexType]
public class Aptitude
{       
    public string CertificateName { get; set; }
 
    public string IssuingAgency { get; set; }
}

my test code is:

class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
services.AddDbContext(options =>
options.UseMongoDb("mongodb://localhost"));

        var sp = services.BuildServiceProvider();
        var context = sp.GetService<MongoContext>();

        var customer = new Customer { EnterpriseName = "ROZH" };
        context.Customers.Add(customer);
        context.SaveChanges();

        var c1 = context.Customers.FirstOrDefault(p => p.EnterpriseName == "ROZH");
        c1.Aptitudes.Add(new Aptitude { CertificateName = "AA", IssuingAgency = "XHB" });
        var m = context.Update(c1);
        var s = m.State;
        context.SaveChanges(acceptAllChangesOnSuccess:true);            
        Console.ReadKey();
    }
}

customer save success,then I add a child Aptitudes instance,but can not save

MissingMethodException in Blueshift.EntityFrameworkCore.MongoDB.Metadata.Conventions.MongoDbRegisterKnownTypesConvention.Apply(InternalEntityTypeBuilder entityTypeBuilder) when using EF Core 2.2

Here is the stack trace:

crit: Microsoft.AspNetCore.Hosting.Internal.WebHost[6]
      Application startup exception
System.AggregateException: One or more errors occurred. (Method not found: 'Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(System.Type, Microsoft.EntityFrameworkCore.Metadata.Internal.ConfigurationSource, Boolean)'.) ---> System.MissingMethodException: Method not found: 'Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(System.Type, Microsoft.EntityFrameworkCore.Metadata.Internal.ConfigurationSource, Boolean)'.
   at Blueshift.EntityFrameworkCore.MongoDB.Metadata.Conventions.MongoDbRegisterKnownTypesConvention.Apply(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnEntityTypeAdded(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.RunVisitor.VisitOnEntityTypeAdded(OnEntityTypeAddedNode node)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnEntityTypeAddedNode.Accept(ConventionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionVisitor.Visit(ConventionNode node)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionVisitor.VisitConventionScope(ConventionScope node)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Run()
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Dispose()
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(TypeIdentity& type, ConfigurationSource configurationSource, Boolean allowOwned, Boolean throwOnQuery)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(Type type, ConfigurationSource configurationSource, Boolean allowOwned, Boolean throwOnQuery)
   at Microsoft.EntityFrameworkCore.ModelBuilder.Entity(Type type)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelCustomizer.FindSets(ModelBuilder modelBuilder, DbContext context)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelCustomizer.Customize(ModelBuilder modelBuilder, DbContext context)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass5_0.<GetModel>b__1()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_2(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.Set[TEntity]()
   at Blueshift.Identity.MongoDB.MongoDbUserStore`8.get_Users()
   at Blueshift.Identity.MongoDB.MongoDbUserStore`8.FindByEmailAsync(String normalizedEmail, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.UserManager`1.FindByEmailAsync(String email)
   at WorkApp.Startup.CreateRoles(IServiceProvider serviceProvider) in C:\Users\AkiSha\source\repos\Projects\WorkApp\WorkApp\Startup.cs:line 193
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at WorkApp.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env) in C:\Users\AkiSha\source\repos\Projects\WorkApp\WorkApp\Startup.cs:line 174
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Internal.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder builder)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
---> (Inner Exception #0) System.MissingMethodException: Method not found: 'Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(System.Type, Microsoft.EntityFrameworkCore.Metadata.Internal.ConfigurationSource, Boolean)'.
   at Blueshift.EntityFrameworkCore.MongoDB.Metadata.Conventions.MongoDbRegisterKnownTypesConvention.Apply(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnEntityTypeAdded(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.RunVisitor.VisitOnEntityTypeAdded(OnEntityTypeAddedNode node)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnEntityTypeAddedNode.Accept(ConventionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionVisitor.Visit(ConventionNode node)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionVisitor.VisitConventionScope(ConventionScope node)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Run()
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Dispose()
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(TypeIdentity& type, ConfigurationSource configurationSource, Boolean allowOwned, Boolean throwOnQuery)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(Type type, ConfigurationSource configurationSource, Boolean allowOwned, Boolean throwOnQuery)
   at Microsoft.EntityFrameworkCore.ModelBuilder.Entity(Type type)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelCustomizer.FindSets(ModelBuilder modelBuilder, DbContext context)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelCustomizer.Customize(ModelBuilder modelBuilder, DbContext context)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass5_0.<GetModel>b__1()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_2(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.Set[TEntity]()
   at Blueshift.Identity.MongoDB.MongoDbUserStore`8.get_Users()
   at Blueshift.Identity.MongoDB.MongoDbUserStore`8.FindByEmailAsync(String normalizedEmail, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.UserManager`1.FindByEmailAsync(String email)
   at WorkApp.Startup.CreateRoles(IServiceProvider serviceProvider) in C:\Users\AkiSha\source\repos\Projects\WorkApp\WorkApp\Startup.cs:line 193<---

Missing Implementation for method 'get_Info'

Good Evening,

I'm building an ASP.NET Core 3.1 app with MongoDB. When I use your Package, I get the following Exception:

"Method 'get_Info' in type 'Blueshift.EntityFrameworkCore.MongoDB.Infrastructure.MongoDbOptionsExtension' from assembly 'Blueshift.EntityFrameworkCore.MongoDB, Version=2.2.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation."

It triggers, when the dependency injector tries to access the database context for the first time. I.e. trying to access a ressource in the database.

Is it a compatibility Issue?

BsonSerializationException when dealing with interfaces

How to reproduce:

  1. Run the project.
  2. Add a car and fill the info.
  3. Stop the mongo server.*
  4. Run the mongo server and run the project again.
  5. Refresh couple of times, and this exception will show:
BsonSerializationException: Unknown discriminator value 'Employee'.
MongoDB.Bson.Serialization.BsonSerializer.LookupActualType(Type nominalType, BsonValue discriminator)

FormatException: An error occurred while deserializing the Owner property of class EFMongoDemo.Web.Models.Car: Unknown discriminator value 'Employee'.
MongoDB.Driver.Linq.MongoQueryProviderImpl.Execute(Expression expression)

This happens on the call:

var cars = await _context.Cars.ToListAsync();

And I noticed there isn't a collection called owner in the db after using the interface.

self refrence still can not work

public class Area
{
[BsonId]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public ObjectId Id { get; private set; }
public string Name { get; set; }
public string Code { get; set; }
public virtual Area Parent { get; set; }
public virtual ICollection Areas { get; set; }
}

my class is area ,has child ICollection Areas,which is self refrence,
save can success,but can not read,use include still not work

Problem with installation

Hi,
i cannot install your package on clean console app (.net core 2.0).

Error:
"Unable to find package Microsoft.EntityFrameworkCore with version (>= 2.1.0-preview1-28051)"
"Unable to find package Microsoft.Extensions.Configuration with version (>= 2.1.0-preview1-28051)"¨

Thanks

Still i got this Efcore internal classes problem

MissingMethodException: Method not found: 'Microsoft.EntityFrameworkCore.Metadata.Internal.InternalEntityTypeBuilder Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(System.Type, Microsoft.EntityFrameworkCore.Metadata.Internal.ConfigurationSource)'.

How to use relations with this?

I was testing this provider and tried using navigation properties to see how it stores related data. I wanted to see if it stored related documents as nested documents or used foreign keys using the ObjectIds. These are my models:

// Models/Dog.cs

using System.ComponentModel.DataAnnotations;
using MongoDB.Bson;

namespace AspNetMvc.Models
{
    public class Dog
    {
        [Key]
        public ObjectId Id { get; set; }

        public string Breed { get; set; }

        public string Name { get; set; }

        //public Owner Owner { get; set; }
    }
}
// Models/Owner.cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using MongoDB.Bson;

namespace AspNetMvc.Models
{
    public class Owner
    {
        [Key]
        public ObjectId Id { get; set; }

        public string Name { get; set; }

        public List<Dog> Dogs { get; set; } = new List<Dog>();
    }
}

The first problem I encountered was getting a StackOverflowException when attempting to use the navigation properties before commenting out Dog's Owner property. It only worked when I had the navigation property on one side.

Then, when I used the following code to create the data:

// Controllers/HomeController.cs

var borky = new Dog
{
    Breed = "Fluffer",
    Name = "Borky"
};

await _db.Dogs.AddAsync(borky);
await _db.SaveChangesAsync();

var newOwner = new Owner { Name = "Bob" };

await _db.Owners.AddAsync(newOwner);
await _db.SaveChangesAsync();

newOwner.Dogs.Add(borky);

await _db.SaveChangesAsync();

It ended up creating the "many" side (Dog) as a separate document without an Owner foreign key, and the Owner was created as a document with an array property called Dogs but it was empty. The data looked like this:


Is there something wrong with the way I'm using relations here?

DbSet.Find throws InvalidOperationException

Hi @crhairr , zooDbContext.Employees .Find(ObjectId.GenerateNewId()) will throw exception "System.InvalidOperationException : The operands for operator 'Equal' do not match the parameters of method 'op_Equality'". Please help to investigate it. It also blocks my project.

.ToTable() equivalent

Hi Chris, is there some equivalent way of setting the mongodb collection name on the OnModelCreating method, like the relational database variant Microsoft.EntityFrameworkCore.RelationalEntityTypeBuilderExtensions.ToTable()?

System.ObjectDisposedException: MongoDbQueryCompilationContextFactory

Hello,

i have this issues: "ObjectDisposedException"

System.ObjectDisposedException: "Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances."

`
public class MongoDbQueryCompilationContextFactory : QueryCompilationContextFactory
{
///
public MongoDbQueryCompilationContextFactory(
[NotNull] QueryCompilationContextDependencies dependencies)
: base(dependencies)
{
}

    /// <inheritdoc />
    public override QueryCompilationContext Create(bool async)
        => new QueryCompilationContext(
            Dependencies,
            async
                ? (ILinqOperatorProvider)new AsyncLinqOperatorProvider()
                : new LinqOperatorProvider(),
            `TrackQueryResults);

}
`

Package is expecting wrong version of Microsoft.EntityFrameworkCore

When I run the following command:
Install-Package Blueshift.EntityFrameworkCore.MongoDB -Version 2.0.0-preview-t0045b4d83 -Source https://www.myget.org/F/efcore-mongodb/api/v3/index.json

I get this warning in the output:
Detected package downgrade: Microsoft.EntityFrameworkCore from 2.0.0-preview1-24639 to 1.1.1
MyApp (>= 1.0.0) -> Blueshift.EntityFrameworkCore.MongoDB (>= 2.0.0-preview-t0045b4d83) -> Microsoft.EntityFrameworkCore (>= 2.0.0-preview1-24639)
MyApp (>= 1.0.0) -> Microsoft.EntityFrameworkCore (>= 1.1.1)

When I try and use the following in my app:
optionsBuilder.UseMongoDb(mongoClient);

I get the following error:
Severity Code Description Project File Line Suppression State
Error CS1705 Assembly 'Blueshift.EntityFrameworkCore.MongoDB' with identity 'Blueshift.EntityFrameworkCore.MongoDB, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' uses 'Microsoft.EntityFrameworkCore, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' which has a higher version than referenced assembly 'Microsoft.EntityFrameworkCore' with identity 'Microsoft.EntityFrameworkCore, Version=1.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' MyApp C:\Users\user\documents\visual studio 2017\Projects\MyApp\MyApp\Model\MongoDbContext.cs 31 Active

Support for complex property

Now that EF Core support for complex properties called Owned types, we can have this implementation on mongodb implementation and insert a collection in the same document. Once they finish the feature.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.