提交 ba2e917e 编写于 作者: 麦壳饼's avatar 麦壳饼

QuerySplittingBehavior 问题调整。

上级 9f536da0
......@@ -60,6 +60,8 @@ namespace IoTSharp.Contracts
}
public class AppSettings
{
private DateTime shardingBeginTime;
public string JwtKey { get; set; }
public string JwtIssuer { get; set; }
public string JwtAudience { get; set; }
......@@ -94,6 +96,42 @@ namespace IoTSharp.Contracts
public DataBaseType DataBase { get; set; } = DataBaseType.PostgreSql;
public int RuleCachingExpiration { get; set; } = 60;
public ShardingByDateMode ShardingByDateMode { get; set; } = ShardingByDateMode.PerMonth;
public DateTime ShardingBeginTime {
get => shardingBeginTime;
set
{
if (value == DateTime.MinValue || value.Year <= 1970)
{
switch (ShardingByDateMode)
{
case ShardingByDateMode.PerMinute:
shardingBeginTime = DateTime.Now.AddMinutes(-5);
break;
case ShardingByDateMode.PerHour:
shardingBeginTime = DateTime.Now.AddHours(-1);
break;
case ShardingByDateMode.PerDay:
shardingBeginTime = DateTime.Now.AddDays(-1).Date;
break;
case ShardingByDateMode.PerMonth:
shardingBeginTime = DateTime.Now.AddMonths(-1).Date;
break;
case ShardingByDateMode.PerYear:
shardingBeginTime = DateTime.Now.AddYears(-1).Date;
break;
default:
shardingBeginTime = value;
break;
}
}
else
{
shardingBeginTime = value;
}
}
}
}
public enum ShardingByDateMode
{
......
......@@ -18,7 +18,7 @@ namespace Microsoft.Extensions.DependencyInjection
services.AddSingleton<IDataBaseModelBuilderOptions>(c => new CassandraModelBuilderOptions());
services.AddDbContextPool<ApplicationDbContext>(builder =>
{
builder.UseCassandra(connectionString, "", s => s.MigrationsAssembly("IoTSharp.Data.Cassandra"));
builder.UseCassandra(connectionString, "", s => s.MigrationsAssembly("IoTSharp.Data.Cassandra").UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
builder.UseInternalServiceProvider(services.BuildServiceProvider());
}
, poolSize);
......
......@@ -3,6 +3,7 @@ using ClickHouse.EntityFrameworkCore.Extensions;
using HealthChecks.Clickhouse.DependencyInjection;
using IoTSharp.Data;
using IoTSharp.Data.ClickHouse;
using Microsoft.EntityFrameworkCore;
namespace Microsoft.Extensions.DependencyInjection
{
......@@ -14,7 +15,7 @@ namespace Microsoft.Extensions.DependencyInjection
services.AddSingleton<IDataBaseModelBuilderOptions>(c => new ClickHouseModelBuilderOptions());
services.AddDbContextPool<ApplicationDbContext>(builder =>
{
builder.UseClickHouse(connectionString, s => s.MigrationsAssembly("IoTSharp.Data.ClickHouse"));
builder.UseClickHouse(connectionString, s => s.MigrationsAssembly("IoTSharp.Data.ClickHouse").UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
builder.UseInternalServiceProvider(services.BuildServiceProvider());
}, poolSize);
checksBuilder.AddClickHouseHealthCheck(connectionString, name: "IoTSharp.Data.ClickHouse");
......
......@@ -30,7 +30,7 @@ namespace Microsoft.Extensions.DependencyInjection
services.AddDbContextPool<ApplicationDbContext>(builder =>
{
builder.UseInternalServiceProvider(services.BuildServiceProvider());
builder.UseMySql(connectionString, serverVersion, s => s.MigrationsAssembly("IoTSharp.Data.MySQL"));
builder.UseMySql(connectionString, serverVersion, s => s.MigrationsAssembly("IoTSharp.Data.MySQL").UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
}
, poolSize );
......
......@@ -20,7 +20,7 @@ namespace Microsoft.Extensions.DependencyInjection
services.AddSingleton<IDataBaseModelBuilderOptions>( c=> new OracleModelBuilderOptions());
services.AddDbContextPool<ApplicationDbContext>(builder =>
{
builder.UseOracle(connectionString, s => s.MigrationsAssembly("IoTSharp.Data.Oracle"));
builder.UseOracle(connectionString, s => s.MigrationsAssembly("IoTSharp.Data.Oracle").UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
builder.UseInternalServiceProvider(services.BuildServiceProvider());
}
, poolSize);
......
......@@ -20,7 +20,7 @@ namespace Microsoft.Extensions.DependencyInjection
services.AddSingleton<IDataBaseModelBuilderOptions>( c=> new NpgsqlModelBuilderOptions());
services.AddDbContextPool<ApplicationDbContext>(builder =>
{
builder.UseNpgsql(connectionString, s => s.MigrationsAssembly("IoTSharp.Data.PostgreSQL"));
builder.UseNpgsql(connectionString, s => s.MigrationsAssembly("IoTSharp.Data.PostgreSQL").UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
builder.UseInternalServiceProvider(services.BuildServiceProvider());
}
, poolSize);
......
......@@ -20,7 +20,7 @@ namespace Microsoft.Extensions.DependencyInjection
services.AddSingleton<IDataBaseModelBuilderOptions>( c=> new MsSqlModelBuilderOptions());
services.AddDbContextPool<ApplicationDbContext>(builder =>
{
builder.UseSqlServer(connectionString, s => s.MigrationsAssembly("IoTSharp.Data.SqlServer"));
builder.UseSqlServer(connectionString, s => s.MigrationsAssembly("IoTSharp.Data.SqlServer").UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
builder.UseInternalServiceProvider(services.BuildServiceProvider());
}
, poolSize);
......
......@@ -27,7 +27,8 @@ namespace Microsoft.Extensions.DependencyInjection
services.AddSingleton<IDataBaseModelBuilderOptions>( c=> new SqliteModelBuilderOptions());
services.AddDbContextPool<ApplicationDbContext>(builder =>
{
builder.UseSqlite(connectionString, s => s.MigrationsAssembly("IoTSharp.Data.Sqlite"));
builder.UseSqlite(connectionString, s => s.MigrationsAssembly("IoTSharp.Data.Sqlite").UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery));
builder.UseInternalServiceProvider(services.BuildServiceProvider());
}
, poolSize);
......
......@@ -8,9 +8,7 @@ using System.Threading.Tasks;
namespace IoTSharp.Data.Configurations
{
/// <summary>
/// https://github.com/Coldairarrow/EFCore.Sharding/issues/60
/// </summary>
public class TelemetryDataConfiguration : IEntityTypeConfiguration<TelemetryData>
{
public void Configure(EntityTypeBuilder<TelemetryData> builder)
......
......@@ -17,15 +17,15 @@ namespace IoTSharp.Data
{
var deviceIdentity = from id in _context.DeviceIdentities.Include(di => di.Device) where id.IdentityId == access_token && id.IdentityType == IdentityType.AccessToken select id;
var devices = from dev in _context.Device.Include(g=>g.Customer).Include(g=>g.Tenant) where deviceIdentity.Any() && dev.Id == deviceIdentity.FirstOrDefault().Device.Id select dev;
bool ok = deviceIdentity == null || !devices.Any();
return (ok, devices.FirstOrDefault());
bool ok = deviceIdentity == null || !devices.AsSplitQuery().Any();
return (ok, devices.AsSplitQuery().FirstOrDefault());
}
public static (bool ok, Device device) GetDeviceByToken(this ApplicationDbContext _context, string access_token)
{
var deviceIdentity = from id in _context.DeviceIdentities.Include(di => di.Device) where id.IdentityId == access_token && id.IdentityType == IdentityType.AccessToken select id;
var deviceIdentity = from id in _context.DeviceIdentities.Include(di => di.Device).AsSingleQuery() where id.IdentityId == access_token && id.IdentityType == IdentityType.AccessToken select id;
var devices = from dev in _context.Device where deviceIdentity.Any() && dev.Id == deviceIdentity.FirstOrDefault().Device.Id select dev;
bool ok = deviceIdentity == null || !devices.Any();
return (ok, devices.FirstOrDefault());
bool ok = deviceIdentity == null || !devices.AsSplitQuery().Any();
return (ok, devices.AsSplitQuery().FirstOrDefault());
}
/// <summary>
/// Save Data to Device's and <typeparamref name="L"/>
......
......@@ -16,14 +16,14 @@ namespace IoTSharp.Data.Extensions
OriginatorType originatorType = cad.OriginatorType;
if (cad.OriginatorType == OriginatorType.Device || cad.OriginatorType == OriginatorType.Gateway || cad.OriginatorType == OriginatorType.Unknow)
{
var dev = _context.Device.Include(d=>d.Tenant).Include(d=>d.Customer).FirstOrDefault(d => d.Id.ToString() == cad.OriginatorName || d.Name == cad.OriginatorName);
var dev = _context.Device.Include(d=>d.Tenant).Include(d=>d.Customer).AsSplitQuery().FirstOrDefault(d => d.Id.ToString() == cad.OriginatorName || d.Name == cad.OriginatorName);
if (dev != null)
{
if (dev.DeviceType == DeviceType.Gateway)
{
if (dev.Id.ToString() != cad.OriginatorName && dev.Name != cad.OriginatorName)
{
var subdev = from g in _context.Device.Include(d => d.Tenant).Include(d => d.Customer).Include(g => g.Owner) where g.Owner == dev && g.Name == cad.OriginatorName select g;
var subdev = from g in _context.Device.Include(d => d.Tenant).Include(d => d.Customer).Include(g => g.Owner).AsSplitQuery() where g.Owner == dev && g.Name == cad.OriginatorName select g;
var orig = await subdev.FirstOrDefaultAsync();
OriginatorId = orig.Id;
originatorType = OriginatorType.Device;
......@@ -51,7 +51,7 @@ namespace IoTSharp.Data.Extensions
}
else if (cad.OriginatorType == OriginatorType.Asset)
{
var ass = _context.Assets.Include(a => a.Tenant).Include(a => a.Customer).FirstOrDefault(d => d.Id.ToString() == cad.OriginatorName || d.Name == cad.OriginatorName);
var ass = _context.Assets.Include(a => a.Tenant).Include(a => a.Customer).AsSplitQuery().FirstOrDefault(d => d.Id.ToString() == cad.OriginatorName || d.Name == cad.OriginatorName);
if (ass != null)
{
originatorType = OriginatorType.Asset;
......
......@@ -58,7 +58,7 @@ namespace IoTSharp.Data.Extensions
public static async Task<DeviceRule[]> GerDeviceRulesList(this ApplicationDbContext _dbContext, Guid devid, MountType mountType)
{
DeviceRule[] lst = null;
var r = from dr in _dbContext.DeviceRules.Include(d => d.Device).Include(d => d.FlowRule) where dr.Device.Id == devid && dr.FlowRule.MountType == mountType select dr ;
var r = from dr in _dbContext.DeviceRules.Include(d => d.Device).Include(d => d.FlowRule).AsSplitQuery() where dr.Device.Id == devid && dr.FlowRule.MountType == mountType select dr ;
if (r.Any())
{
lst = await r.ToArrayAsync();
......
......@@ -311,7 +311,7 @@ namespace IoTSharp.Controllers
{
await _signInManager.SignInAsync(user, false);
await _signInManager.UserManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, model.Email));
var customer = await _context.Customer.Include(c => c.Tenant).FirstOrDefaultAsync(c => c.Email == model.Customer);
var customer = await _context.Customer.Include(c => c.Tenant).AsSingleQuery().FirstOrDefaultAsync(c => c.Email == model.Customer);
if (customer != null)
{
await _signInManager.UserManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, model.Email));
......
......@@ -57,7 +57,7 @@ namespace IoTSharp.Controllers
[HttpGet]
public async Task<ApiResult<List<AssetRelation>>> AssetRelations(Guid assetid)
{
var result = await _context.Assets.Include(c => c.OwnedAssets).SingleOrDefaultAsync(c => c.Id == assetid);
var result = await _context.Assets.Include(c => c.OwnedAssets).AsSingleQuery().SingleOrDefaultAsync(c => c.Id == assetid);
return new ApiResult<List<AssetRelation>>(ApiCode.Success, "OK", result?.OwnedAssets);
......@@ -72,7 +72,7 @@ namespace IoTSharp.Controllers
var profile = this.GetUserProfile();
var result = _context.Assets.Include(c => c.OwnedAssets)
var result = _context.Assets.Include(c => c.OwnedAssets).AsSingleQuery()
.SingleOrDefault(x =>
x.Id == assetid && x.Customer.Id == profile.Comstomer && x.Tenant.Id == profile.Tenant)?.OwnedAssets
.ToList().GroupBy(c => c.DeviceId).Select(c => new
......@@ -114,7 +114,7 @@ namespace IoTSharp.Controllers
public async Task<ApiResult<AssetDto>> Get(Guid id)
{
var profile = this.GetUserProfile();
var asset = await _context.Assets.Include(c => c.Customer).Include(c => c.Tenant).SingleOrDefaultAsync(c =>
var asset = await _context.Assets.Include(c => c.Customer).Include(c => c.Tenant).AsSingleQuery().SingleOrDefaultAsync(c =>
c.Id == id && c.Customer.Id == profile.Comstomer && c.Tenant.Id == profile.Tenant);
if (asset != null)
{
......@@ -137,7 +137,7 @@ namespace IoTSharp.Controllers
{
var profile = this.GetUserProfile();
var asset = await _context.Assets.Include(c => c.Customer).Include(c => c.Tenant).SingleOrDefaultAsync(c =>
var asset = await _context.Assets.Include(c => c.Customer).Include(c => c.Tenant).AsSingleQuery().SingleOrDefaultAsync(c =>
c.Id == dto.Id && c.Customer.Id == profile.Comstomer && c.Tenant.Id == profile.Tenant);
if (asset == null)
{
......@@ -198,7 +198,7 @@ namespace IoTSharp.Controllers
try
{
var asset = await _context.Assets.Include(c => c.Customer).Include(c => c.Tenant)
.Include(c => c.OwnedAssets).SingleOrDefaultAsync(c =>
.Include(c => c.OwnedAssets).AsSingleQuery().SingleOrDefaultAsync(c =>
c.Id == id && c.Customer.Id == profile.Comstomer && c.Tenant.Id == profile.Tenant);
if (asset == null)
{
......@@ -227,7 +227,7 @@ namespace IoTSharp.Controllers
try
{
var asset = await _context.Assets.Include(c => c.Customer).Include(c => c.Tenant)
.Include(c => c.OwnedAssets).SingleOrDefaultAsync(c =>
.Include(c => c.OwnedAssets).AsSingleQuery().SingleOrDefaultAsync(c =>
c.Id == m.AssetId && c.Customer.Id == profile.Comstomer && c.Tenant.Id == profile.Tenant);
if (asset == null)
{
......@@ -289,7 +289,7 @@ namespace IoTSharp.Controllers
try
{
var asset = await _context.Assets.Include(c => c.Customer).Include(c => c.Tenant)
.Include(c => c.OwnedAssets).SingleOrDefaultAsync(c =>
.Include(c => c.OwnedAssets).AsSingleQuery().SingleOrDefaultAsync(c =>
c.Id == m.AssetId && c.Customer.Id == profile.Comstomer && c.Tenant.Id == profile.Tenant);
await _context.SaveChangesAsync();
......
......@@ -139,7 +139,7 @@ namespace IoTSharp.Controllers
return new ApiResult<PagedData<DeviceDetailDto>>(ApiCode.Success, "OK", new PagedData<DeviceDetailDto>
{
total = await _context.Device.CountAsync(condition),
rows = _context.Device.Include(c => c.DeviceIdentity).OrderByDescending(c => c.LastActive).Where(condition).Skip((m.offset) * m.limit).Take(m.limit).ToList().Select(x => new DeviceDetailDto()
rows = _context.Device.Include(c => c.DeviceIdentity).OrderByDescending(c => c.LastActive).Where(condition).Skip((m.offset) * m.limit).Take(m.limit).AsSingleQuery().ToList().Select(x => new DeviceDetailDto()
{
Id = x.Id,
Name = x.Name,
......@@ -241,8 +241,8 @@ namespace IoTSharp.Controllers
[ProducesDefaultResponseType]
public async Task<ApiResult<DeviceIdentity>> CreateX509Identity(Guid deviceId)
{
var did = await _context.DeviceIdentities.Include(d => d.Device).FirstOrDefaultAsync(c => c.Device.Id == deviceId);
var cust = from c in _context.Device.Include(d => d.Customer).Include(d => d.Tenant) where c.Id == deviceId select c;
var did = await _context.DeviceIdentities.Include(d => d.Device).AsSingleQuery().FirstOrDefaultAsync(c => c.Device.Id == deviceId);
var cust = from c in _context.Device.Include(d => d.Customer).Include(d => d.Tenant).AsSplitQuery() where c.Id == deviceId select c;
var dev = cust.FirstOrDefault();
if (did != null && dev != null)
{
......@@ -286,7 +286,7 @@ namespace IoTSharp.Controllers
{
try
{
var dt = _context.DeviceIdentities.Include(d => d.Device).FirstOrDefault(c => c.Device.Id == deviceId);
var dt = _context.DeviceIdentities.Include(d => d.Device).AsSingleQuery().FirstOrDefault(c => c.Device.Id == deviceId);
if (dt == null || dt.IdentityType != IdentityType.X509Certificate || string.IsNullOrEmpty(dt.IdentityValue))
{
return Ok(new ApiResult(ApiCode.NotFoundDevice, "未找到设备或设备公钥、秘钥为空"));
......@@ -415,12 +415,12 @@ namespace IoTSharp.Controllers
if (User.IsInRole(nameof(UserRole.TenantAdmin)))
{
var tid =Guid.Parse( User.Claims.First(c => c.Type == IoTSharpClaimTypes.Tenant).Value);
dev = await _context.Device.Include(d => d.Tenant).FirstOrDefaultAsync(d => d.Id == deviceId && d.Tenant.Id == tid && d.Status > -1);
dev = await _context.Device.Include(d => d.Tenant).AsSingleQuery().FirstOrDefaultAsync(d => d.Id == deviceId && d.Tenant.Id == tid && d.Status > -1);
}
else if (User.IsInRole(nameof(UserRole.NormalUser)))
{
var cid = Guid.Parse( User.Claims.First(c => c.Type == IoTSharpClaimTypes.Customer).Value);
dev = await _context.Device.Include(d => d.Customer).FirstOrDefaultAsync(d => d.Id == deviceId && d.Customer.Id == cid && d.Status > -1);
dev = await _context.Device.Include(d => d.Customer).AsSingleQuery().FirstOrDefaultAsync(d => d.Id == deviceId && d.Customer.Id == cid && d.Status > -1);
}
return dev;
}
......@@ -609,7 +609,7 @@ namespace IoTSharp.Controllers
var cid = User.Claims.First(c => c.Type == IoTSharpClaimTypes.Customer);
var tid = User.Claims.First(c => c.Type == IoTSharpClaimTypes.Tenant);
var dev = _context.Device.Include(d => d.Tenant).Include(d => d.Customer).First(d => d.Id == device.Id);
var dev = _context.Device.Include(d => d.Tenant).Include(d => d.Customer).AsSplitQuery().First(d => d.Id == device.Id);
var tenid = dev.Tenant.Id;
var cusid = dev.Customer.Id;
......@@ -658,7 +658,7 @@ namespace IoTSharp.Controllers
[ProducesDefaultResponseType]
public async Task<ApiResult<Device>> PostDevice(Guid id, DevicePostProduceDto device)
{
var produce = await _context.Produces.Include(p=>p.DefaultAttributes).FirstOrDefaultAsync( p=>p.Id==id);
var produce = await _context.Produces.Include(p=>p.DefaultAttributes).AsSplitQuery().FirstOrDefaultAsync( p=>p.Id==id);
if (produce== null)
{
return new ApiResult<Device>(ApiCode.NotFoundProduce, "Not found Produce", null);
......
......@@ -57,7 +57,7 @@ namespace IoTSharp.Controllers
[HttpGet]
public async Task<ApiResult<List<ProduceData>>> ProduceDatas(Guid produceid)
{
var result = await _context.ProduceDatas.Include(c => c.Owner).Where(p=>p.Owner.Id==produceid).ToListAsync();
var result = await _context.ProduceDatas.Include(c => c.Owner).Where(p=>p.Owner.Id==produceid).AsSplitQuery().ToListAsync();
return new ApiResult<List<ProduceData>>(ApiCode.Success, "OK", result);
}
......
......@@ -305,7 +305,7 @@ namespace IoTSharp.Controllers
{
var profile = this.GetUserProfile();
var map = await _context.DeviceRules.Include(c => c.Device)
.Include(c => c.FlowRule).FirstOrDefaultAsync(c => c.FlowRule.RuleId == ruleId && c.Device.Id == deviceId && c.Device.Tenant.Id == profile.Tenant && c.FlowRule.Tenant.Id == profile.Tenant);
.Include(c => c.FlowRule).AsSplitQuery().FirstOrDefaultAsync(c => c.FlowRule.RuleId == ruleId && c.Device.Id == deviceId && c.Device.Tenant.Id == profile.Tenant && c.FlowRule.Tenant.Id == profile.Tenant);
if (map != null)
{
_context.DeviceRules.Remove(map);
......@@ -319,7 +319,7 @@ namespace IoTSharp.Controllers
public ApiResult<List<FlowRule>> GetDeviceRules(Guid deviceId)
{
var profile = this.GetUserProfile();
return new ApiResult<List<FlowRule>>(ApiCode.Success, "Ok", _context.DeviceRules.Include(c => c.Device).Where(c => c.Device.Id == deviceId && c.Device.Tenant.Id == profile.Tenant).Select(c => c.FlowRule).Select(c => new FlowRule() { RuleId = c.RuleId, CreatTime = c.CreatTime, Name = c.Name, RuleDesc = c.RuleDesc }).ToList());
return new ApiResult<List<FlowRule>>(ApiCode.Success, "Ok", _context.DeviceRules.Include(c => c.Device).Where(c => c.Device.Id == deviceId && c.Device.Tenant.Id == profile.Tenant).Select(c => c.FlowRule).Select(c => new FlowRule() { RuleId = c.RuleId, CreatTime = c.CreatTime, Name = c.Name, RuleDesc = c.RuleDesc }).AsSplitQuery().ToList());
}
[HttpGet("[action]")]
......@@ -350,7 +350,7 @@ namespace IoTSharp.Controllers
}).Skip(m.offset * m.limit).Take(m.limit).ToListAsync();
var total =await _context.DeviceRules.Include(c => c.FlowRule).Include(c => c.Device).Where(condition).Select(c=>c.Device).CountAsync();
var total =await _context.DeviceRules.Include(c => c.FlowRule).Include(c => c.Device).Where(condition).Select(c=>c.Device).AsSplitQuery().CountAsync();
return new ApiResult<PagedData<DeviceRuleDto>>(ApiCode.Success, "Ok", new PagedData<DeviceRuleDto> { rows=rows,total= total });
}
......@@ -370,7 +370,7 @@ namespace IoTSharp.Controllers
var activity = JsonConvert.DeserializeObject<Activity>(m.Biz);
var CreatorId = Guid.NewGuid();
var CreateDate = DateTime.Now;
var rule = _context.FlowRules.Include(c => c.Customer).Include(c => c.Tenant).FirstOrDefault(c => c.RuleId == activity.RuleId);
var rule = _context.FlowRules.Include(c => c.Customer).Include(c => c.Tenant).AsSplitQuery().FirstOrDefault(c => c.RuleId == activity.RuleId);
rule.DefinitionsXml = m.Xml;
rule.Creator = profile.Id.ToString();
rule.CreateId = CreatorId;
......@@ -1235,8 +1235,8 @@ namespace IoTSharp.Controllers
public ApiResult<dynamic> GetFlowOperations(Guid eventId)
{
var profile = this.GetUserProfile();
var _event = _context.BaseEvents.Include(c=>c.FlowRule).SingleOrDefault(c => c.EventId == eventId);
var _operations = _context.FlowOperations.Include(c=>c.Flow).Where(c => c.BaseEvent == _event).ToList();
var _event = _context.BaseEvents.Include(c=>c.FlowRule).AsSplitQuery().SingleOrDefault(c => c.EventId == eventId);
var _operations = _context.FlowOperations.Include(c=>c.Flow).Where(c => c.BaseEvent == _event).AsSplitQuery().ToList();
......
......@@ -99,7 +99,7 @@ namespace IoTSharp
/// <param name="custId"></param>
/// <returns></returns>
public static Customer GetCustomer(this ApplicationDbContext context, Guid custId)
=> context.Customer.Include(c => c.Tenant).FirstOrDefault(c => c.Id == custId);
=> context.Customer.Include(c => c.Tenant).AsSingleQuery().FirstOrDefault(c => c.Id == custId);
/// <summary>
/// 获取指定的租户信息
/// </summary>
......@@ -321,7 +321,7 @@ namespace IoTSharp
if (devname != "me" && device.DeviceType == DeviceType.Gateway)
{
var ch = from g in _dbContext.Gateway.Include(g => g.Tenant).Include(g => g.Customer).Include(c => c.Children) where g.Id == device.Id select g;
var gw = ch.FirstOrDefault();
var gw = ch.AsSplitQuery().FirstOrDefault();
if(gw == null)
{//未处理null的情况
......
......@@ -135,7 +135,7 @@ namespace IoTSharp.FlowRuleEngine
{
using (var context = sp.ServiceProvider.GetRequiredService<ApplicationDbContext>())
{
var r = context.FlowRules.Include(c => c.Customer).Include(c => c.Tenant).FirstOrDefault(c => c.RuleId == rule.RuleId);
var r = context.FlowRules.Include(c => c.Customer).Include(c => c.Tenant).AsSplitQuery().FirstOrDefault(c => c.RuleId == rule.RuleId);
if (r != null)
{
@event.FlowRule = r;
......
......@@ -108,7 +108,7 @@ namespace IoTSharp.Services.CoApResources
default:
break;
}
var mcr = await _dbContext.DeviceIdentities.Include(d => d.Device).FirstOrDefaultAsync(di => di.IdentityType == IdentityType.AccessToken && di.IdentityId == acctoken);
var mcr = await _dbContext.DeviceIdentities.Include(d => d.Device).AsSingleQuery().FirstOrDefaultAsync(di => di.IdentityType == IdentityType.AccessToken && di.IdentityId == acctoken);
var dev = mcr?.Device;
if (mcr != null && dev != null)
{
......
......@@ -176,7 +176,7 @@ namespace IoTSharp.Services
else
{
_logger.LogInformation($"ClientId={obj.ClientId},Endpoint={obj.Endpoint},Username={obj.UserName},Password={obj.Password}");
var mcr = _dbContextcv.DeviceIdentities.Include(d => d.Device).FirstOrDefault(mc =>
var mcr = _dbContextcv.DeviceIdentities.Include(d => d.Device).AsSplitQuery().FirstOrDefault(mc =>
mc.IdentityType == IdentityType.AccessToken && mc.IdentityId == obj.UserName ||
mc.IdentityType == IdentityType.DevicePassword && mc.IdentityId == obj.UserName && mc.IdentityValue == obj.Password);
if (mcr != null)
......@@ -197,7 +197,7 @@ namespace IoTSharp.Services
}
else if (_dbContextcv.AuthorizedKeys.Any(ak => ak.AuthToken == obj.Password))
{
var ak = _dbContextcv.AuthorizedKeys.Include(ak => ak.Customer).Include(ak => ak.Tenant).Include(ak => ak.Devices).FirstOrDefault(ak => ak.AuthToken == obj.Password);
var ak = _dbContextcv.AuthorizedKeys.Include(ak => ak.Customer).Include(ak => ak.Tenant).Include(ak => ak.Devices).AsSplitQuery().FirstOrDefault(ak => ak.AuthToken == obj.Password);
if (ak != null && !ak.Devices.Any(dev => dev.Name == obj.UserName))
{
var devvalue = new Device() { Name = obj.UserName, DeviceType = DeviceType.Device, Timeout = 300, LastActive = DateTime.Now };
......@@ -209,7 +209,7 @@ namespace IoTSharp.Services
_dbContextcv.SaveChanges();
_queue.PublishDeviceStatus(devvalue.Id, DeviceStatus.Good);
}
var mcp = _dbContextcv.DeviceIdentities.Include(d => d.Device).FirstOrDefault(mc => mc.IdentityType == IdentityType.DevicePassword && mc.IdentityId == obj.UserName && mc.IdentityValue == obj.Password);
var mcp = _dbContextcv.DeviceIdentities.Include(d => d.Device).AsSingleQuery().FirstOrDefault(mc => mc.IdentityType == IdentityType.DevicePassword && mc.IdentityId == obj.UserName && mc.IdentityValue == obj.Password);
if (mcp != null)
{
e.SessionItems.Add(nameof(Device), mcp.Device);
......
......@@ -222,15 +222,31 @@ namespace IoTSharp
{
case TelemetryStorage.Sharding:
ShardingByDateMode settingsShardingByDateMode = settings.ShardingByDateMode;
var sbt = DateTime.Now.Subtract( settings.ShardingBeginTime);
services.AddShardingDbContext<ShardingDbContext>().UseRouteConfig(o =>
{
switch (settingsShardingByDateMode)
{
case ShardingByDateMode.PerMinute : o.AddShardingTableRoute<TelemetryDataMinuteRoute>();break;
case ShardingByDateMode.PerHour : o.AddShardingTableRoute<TelemetryDataHourRoute>();break;
case ShardingByDateMode.PerDay : o.AddShardingTableRoute<TelemetryDataDayRoute>();break;
case ShardingByDateMode.PerMonth : o.AddShardingTableRoute<TelemetryDataMonthRoute>();break;
case ShardingByDateMode.PerYear : o.AddShardingTableRoute<TelemetryDataYearRoute>();break;
case ShardingByDateMode.PerMinute:
if (sbt.TotalMinutes < 5) throw new ArgumentException($"按分钟分表时间至少大于当前时间五分钟。");
o.AddShardingTableRoute<TelemetryDataMinuteRoute>();
break;
case ShardingByDateMode.PerHour:
if (sbt.TotalHours < 1) throw new ArgumentException($"按小时分表时间至少大于当前时间一小时。");
o.AddShardingTableRoute<TelemetryDataHourRoute>();
break;
case ShardingByDateMode.PerDay:
if (sbt.TotalDays < 1) throw new ArgumentException($"按日分表时间至少大于当前时间一天。");
o.AddShardingTableRoute<TelemetryDataDayRoute>();
break;
case ShardingByDateMode.PerMonth:
if (sbt.TotalDays < DateTime.Now.Subtract(DateTime.Now.Date.AddDays(-DateTime.Now.Day)).TotalDays) throw new ArgumentException($"按月分表时间至少大于当前时间一个月。");
o.AddShardingTableRoute<TelemetryDataMonthRoute>();
break;
case ShardingByDateMode.PerYear:
if (sbt.TotalDays < DateTime.Now.Subtract(DateTime.Now.Date.AddMonths(-DateTime.Now.Month)).TotalDays) throw new ArgumentException($"按月分表时间至少大于当前时间一个月。");
o.AddShardingTableRoute<TelemetryDataYearRoute>();
break;
default: throw new InvalidOperationException($"unknown sharding mode:{settingsShardingByDateMode}");
}
}).UseConfig(o =>
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册