Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix issues-542 #543

Merged
merged 1 commit into from
Apr 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,20 @@ internal void TryInitializeMasaDbContextOptions(MasaDbContextOptions? options)

try
{
base.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
_ = base.ChangeTracker;
}
catch (InvalidOperationException ex)
{
var logger = Options!.ServiceProvider?.GetService(Options.ContextType) as ILogger;
logger?.LogDebug("Error generating data context", ex);
throw new InvalidOperationException(
"No database provider has been configured for this DbContext. A provider can be configured by overriding the 'MasaDbContext.OnConfiguring' method or by using 'AddMasaDbContext' on the application service provider. If 'AddMasaDbContext' is used, then also ensure that your DbContext type accepts a 'MasaDbContextOptions<TContext>' object in its constructor and passes it to the base constructor for DbContext.");
ILogger? logger = null;
if (options != null)
{
var loggerType = typeof(ILogger<>).MakeGenericType(options.ContextType);
logger = options.ServiceProvider?.GetService(loggerType) as ILogger;
}

logger ??= MasaApp.GetService<ILogger<MasaDbContext>>();
logger?.LogDebug(ex, "Error generating data context");
throw new InvalidOperationException("No database provider has been configured for this DbContext. A provider can be configured by overriding the 'MasaDbContext.OnConfiguring' method or by using 'AddMasaDbContext' on the application service provider. If 'AddMasaDbContext' is used, then also ensure that your DbContext type accepts a 'MasaDbContextOptions<TContext>' object in its constructor and passes it to the base constructor for DbContext.");
}
}

Expand Down Expand Up @@ -158,8 +164,8 @@ protected virtual void ConfigureGlobalFilters<TEntity>(ModelBuilder modelBuilder
if (typeof(IMultiEnvironment).IsAssignableFrom(typeof(TEntity)) && EnvironmentContext != null)
{
Expression<Func<TEntity, bool>> envFilter = entity => !IsEnvironmentFilterEnabled ||
EF.Property<string>(entity, nameof(IMultiEnvironment.Environment))
.Equals(EnvironmentContext != null ? EnvironmentContext.CurrentEnvironment : default);
EF.Property<string>(entity, nameof(IMultiEnvironment.Environment))
.Equals(EnvironmentContext != null ? EnvironmentContext.CurrentEnvironment : default);
expression = envFilter.And(expression != null, expression);
}

Expand All @@ -176,11 +182,12 @@ protected virtual void ConfigureGlobalFilters<TEntity>(ModelBuilder modelBuilder
{
string defaultTenantId = Guid.Empty.ToString();
Expression<Func<TEntity, bool>> tenantFilter = entity => !IsTenantFilterEnabled ||
(EF.Property<Guid>(entity, nameof(IMultiTenant<Guid>.TenantId)).ToString())
.Equals(TenantContext.CurrentTenant != null ? TenantContext.CurrentTenant.Id : defaultTenantId);
(EF.Property<Guid>(entity, nameof(IMultiTenant<Guid>.TenantId)).ToString())
.Equals(TenantContext.CurrentTenant != null ? TenantContext.CurrentTenant.Id : defaultTenantId);

expression = tenantFilter.And(expression != null, expression);
}

return expression;
}

Expand Down Expand Up @@ -294,7 +301,7 @@ public class DefaultMasaDbContext<TMultiTenantId> : DefaultMasaDbContext
{
protected override bool IsTenantFilterEnabled => DataFilter?.IsEnabled<IMultiTenant<TMultiTenantId>>() ?? false;

protected DefaultMasaDbContext()
protected DefaultMasaDbContext() : base()
{
}

Expand All @@ -310,11 +317,12 @@ public DefaultMasaDbContext(MasaDbContextOptions options) : base(options)
{
string defaultTenantId = default(TMultiTenantId)?.ToString() ?? string.Empty;
Expression<Func<TEntity, bool>> tenantFilter = entity => !IsTenantFilterEnabled ||
(EF.Property<TMultiTenantId>(entity, nameof(IMultiTenant<TMultiTenantId>.TenantId)).ToString() ?? string.Empty)
.Equals(TenantContext.CurrentTenant != null ? TenantContext.CurrentTenant.Id : defaultTenantId);
(EF.Property<TMultiTenantId>(entity, nameof(IMultiTenant<TMultiTenantId>.TenantId)).ToString() ?? string.Empty)
.Equals(TenantContext.CurrentTenant != null ? TenantContext.CurrentTenant.Id : defaultTenantId);

expression = tenantFilter.And(expression != null, expression);
}

return expression;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,10 @@ private static IServiceCollection AddCoreServices<TDbContextImplementation>(
{
parameters.Add(serviceProvider.GetService(parameter.ParameterType));
}
var dbContext = parameters.Count > 0 ?
Activator.CreateInstance(typeof(TDbContextImplementation), parameters.ToArray()) as DefaultMasaDbContext :
Activator.CreateInstance(typeof(TDbContextImplementation)) as DefaultMasaDbContext;

var dbContext = parameters.Count > 0
? Activator.CreateInstance(typeof(TDbContextImplementation), parameters.ToArray()) as DefaultMasaDbContext
: Activator.CreateInstance(typeof(TDbContextImplementation)) as DefaultMasaDbContext;
MasaArgumentException.ThrowIfNull(dbContext);

dbContext.TryInitializeMasaDbContextOptions(serviceProvider.GetService<MasaDbContextOptions<TDbContextImplementation>>());
Expand All @@ -57,8 +58,12 @@ private static IServiceCollection AddCoreServices<TDbContextImplementation>(
optionsBuilder?.Invoke(masaBuilder);
return services.AddCoreServices<TDbContextImplementation>((serviceProvider, efDbContextOptionsBuilder) =>
{
efDbContextOptionsBuilder.DbContextOptionsBuilder.UseApplicationServiceProvider(serviceProvider);
masaBuilder.Builder?.Invoke(serviceProvider, efDbContextOptionsBuilder.DbContextOptionsBuilder);
if (masaBuilder.Builder != null)
{
efDbContextOptionsBuilder.DbContextOptionsBuilder.UseApplicationServiceProvider(serviceProvider);
efDbContextOptionsBuilder.DbContextOptionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
masaBuilder.Builder.Invoke(serviceProvider, efDbContextOptionsBuilder.DbContextOptionsBuilder);
}
}, masaBuilder.EnableSoftDelete, optionsLifetime);
}

Expand Down Expand Up @@ -180,7 +185,6 @@ private static IServiceCollection TryAddConfigure<TOptions>(
#pragma warning disable S2094
private sealed class MasaDbContextProvider<TDbContext>
{

}
#pragma warning restore S2094
#pragma warning restore S2326
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ public class CustomDbContext2 : MasaDbContext

public CustomDbContext2(MasaDbContextOptions<CustomDbContext2> options) : base(options)
{
base.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTrackingWithIdentityResolution;
}
}

Expand All @@ -29,6 +30,8 @@ protected override void OnConfiguring(MasaDbContextOptionsBuilder optionsBuilder
{
var connectionString = "data source=customDbContext3";
optionsBuilder.UseSqlite(connectionString);

optionsBuilder.DbContextOptionsBuilder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTrackingWithIdentityResolution);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

using Microsoft.Extensions.Logging;

namespace Masa.Contrib.Data.EFCore.Tests.Scenes.Isolation;

[TestClass]
Expand Down Expand Up @@ -95,6 +97,50 @@ public async Task TestTenantIdByAddOrderAsync()
Assert.AreEqual(2, orderAll.Count);
}

[TestMethod]
public void TestQueryTrackingBehaviorByDefault()
{
var services = new ServiceCollection();
services.AddMasaDbContext<CustomDbContext>(dbContext =>
{
dbContext.UseInMemoryDatabase(Guid.NewGuid().ToString());
dbContext.UseFilter();
});
var rootServiceProvider = services.BuildServiceProvider();

var dbContext = rootServiceProvider.GetRequiredService<CustomDbContext>();
Assert.AreEqual(QueryTrackingBehavior.NoTracking, dbContext.ChangeTracker.QueryTrackingBehavior);
}

[TestMethod]
public void TestCustomQueryTrackingBehaviorByConstructor()
{
var services = new ServiceCollection();
services.AddMasaDbContext<CustomDbContext2>(dbContext =>
{
dbContext.UseInMemoryDatabase(Guid.NewGuid().ToString());
dbContext.UseFilter();
});
var rootServiceProvider = services.BuildServiceProvider();

var dbContext = rootServiceProvider.GetRequiredService<CustomDbContext2>();
Assert.AreEqual(QueryTrackingBehavior.NoTrackingWithIdentityResolution, dbContext.ChangeTracker.QueryTrackingBehavior);
}

[TestMethod]
public void TestCustomQueryTrackingBehaviorByOnConfiguring()
{
var services = new ServiceCollection();
services.AddMasaDbContext<CustomDbContext3>(dbContext =>
{
dbContext.UseFilter();
});
var rootServiceProvider = services.BuildServiceProvider();

var dbContext = rootServiceProvider.GetRequiredService<CustomDbContext3>();
Assert.AreEqual(QueryTrackingBehavior.NoTrackingWithIdentityResolution, dbContext.ChangeTracker.QueryTrackingBehavior);
}

[TestMethod]
public async Task TestTenantIdByAddOrderAndNoConstructorAsync()
{
Expand Down Expand Up @@ -135,6 +181,7 @@ public async Task TestTenantIdByAddOrderAndNoConstructorAsync()
[TestMethod]
public void TestAddMasaDbContextWhenNotUseDatabase()
{
_services.AddLogging(log => log.AddConsole());
_services.AddMasaDbContext<CustomDbContext4>(builder => builder.UseFilter());
var rootServiceProvider = _services.BuildServiceProvider();

Expand Down