I am using Automapper in my application and I faced an issue while mapping Expression>.
I have:
var predicateDto = _mapper.Map<Expression<Func<InventoryApplicationDto, bool>>, Expression<Func<tblInventoryApplication, bool>>>(predicate);
var applications = await _repository.SearchActivePagedAsync(predicateDto, page, pageSize);
This code works fine when I have only one value in predicate but it returns exception when I have List<T> as a predicate.
-- EDIT 1
Service method:
public async Task<PagedResult<InventoryApplicationDto>> SearchActivePagedAsync(
Expression<Func<InventoryApplicationDto, bool>> predicate, int page, int pageSize)
{
try
{
var predicateDto = _mapper.Map<Expression<Func<InventoryApplicationDto, bool>>, Expression<Func<tblInventoryApplication, bool>>>(predicate);
var applications = await _repository.SearchActivePagedAsync(predicateDto, page, pageSize);
var result = new PagedResult<InventoryApplicationDto>
{
CurrentPage = applications.CurrentPage,
PageSize = applications.PageSize,
RowCount = applications.RowCount,
PageCount = applications.PageCount,
Results = _mapper.Map<IEnumerable<tblInventoryApplication>, IEnumerable<InventoryApplicationDto>>(applications.Results)
};
return result;
}
catch (Exception ex)
{
var exc = ex.Message;
throw;
}
}
Controller method:
public async Task<ActionResult> Filter(
List<InventoryRegionDto> regions,
List<InventorySystemDto> systems,
string phrase,
int page = 0, int pageSize = 0)
{
_applicationSearchParamter.Systems = systems;
_applicationSearchParamter.Regions = regions;
_applicationSearchParamter.Phrase = phrase;
var applicationsSearchBuilder = new ApplicationSearchBuilder(_applicationSearchParamter);
var currentPage = page == 0 ? _page : page;
var currentPageSize = pageSize == 0 ? _pageSize : pageSize;
var applications =
await _applicationService.SearchActivePagedAsync(applicationsSearchBuilder.Build(), currentPage, currentPageSize);
return PartialView("~/Views/Applications/_Applications.cshtml", applications);
}
Search builder method:
public Expression<Func<InventoryApplicationDto, bool>> Build()
{
var predicate = PredicateBuilder.New<InventoryApplicationDto>(true);
if (!string.IsNullOrEmpty(_inventoryApplicationSearchParamter.Phrase))
predicate.And(s =>
s.Name.Contains(_inventoryApplicationSearchParamter.Phrase) ||
s.Acronym.Contains(_inventoryApplicationSearchParamter.Phrase) ||
s.DetailedDescription.Contains(_inventoryApplicationSearchParamter.Phrase) ||
s.Comments.Contains(_inventoryApplicationSearchParamter.Phrase)
);
if (_inventoryApplicationSearchParamter.Regions != null &&
_inventoryApplicationSearchParamter.Regions.Any())
{
var predicateTemp = PredicateBuilder.New<InventoryApplicationDto>(true);
foreach (var region in _inventoryApplicationSearchParamter.Regions)
{
predicateTemp.Or(p => p.Region.Id == region.Id);
}
predicate.And(predicateTemp);
}
if (_inventoryApplicationSearchParamter.Systems != null &&
_inventoryApplicationSearchParamter.Systems.Any())
{
var predicateTemp = PredicateBuilder.New<InventoryApplicationDto>(true);
foreach (var system in _inventoryApplicationSearchParamter.Systems)
{
predicateTemp.Or(s => s.Systems.Any(i => i.Id == system.Id));
}
predicate.And(predicateTemp);
}
return predicate;
}
The Inner exception I am getting is :
ParameterExpression of type
'Infrastructure.Domain.tblInventoryApplication' cannot be used
for delegate parameter of type
'Infrastructure.Dto.InventoryApplicationDto'
Related
Hi I am using Entity Framework Code First, I have a collection of Entities that need to be saved, but I have my EF Repository created as below
public T Create(T item)
{
try
{
if (ufb != null && ufb.CurrentUser != null)
{
SetValue("CreatedByUserId", item, ufb.CurrentUser.Id);
SetValue("UpdatedByUserId", item, ufb.CurrentUser.Id);
}
SetValue("DateCreated", item, DateTime.Now);
SetValue("DateUpdated", item, DateTime.Now);
var newEntry = this.DbSet.Add(item);
this.Context.Database.Log = message => LogHandler.LogInfo(1111, message);
try
{
this.Context.SaveChanges();
}
catch (Exception ex)
{
LogHandler.LogInfo(2501, ex.Message);
}
BuildMetaData(item, true, true);
return newEntry;
}
catch (DbEntityValidationException dbEx)
{
// http://forums.asp.net/t/2014382.aspx?Validation+failed+for+one+or+more+entities+See+EntityValidationErrors+property+for+more+details+
string msg = string.Empty;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
msg += validationError.PropertyName;
msg += "---";
msg += validationError.ErrorMessage;
msg += "||";
}
}
throw new Exception("7777 CREATE EntityValidationErrors: " + msg);
}
}
My calling method is as below:
public List<VehicleInfo> Create(List<VehicleInfo> vehicleInfos, string Entity, int EntityId)
{
bool vehicleExists = false; List<VehicleInfo> newVehicleInfos = null;
if ((vehicleInfos != null) && (vehicleInfos.Count > 0))
{
newVehicleInfos = new List<VehicleInfo>();
foreach (VehicleInfo vehicleInfo in vehicleInfos)
{
vehicleExists = false;
if (vehicleInfo != null)
{
vehicleExists = this.VehicleExists(vehicleInfo.VehicleId, Entity, EntityId);
vehicleInfo.Entity = Entity;
vehicleInfo.EntityId = EntityId;
VehicleInfo v = this.UnitOfWork.VehicleInfoRepository.Create(vehicleInfo);
newVehicleInfos.Add(v);
}
}
}
return newVehicleInfos;
}
Hence when I am calling repositories create method for multiple times, its throwing me the above error, any help or suggestion would be very helpful, please thank you.
void BuildMetaDataNoThread(object item, bool active, bool isNew = false)
{
if (item.GetType() != typeof(JsonObject))
{
var dm = new DataAccessUnitOfWork(Constants.DefaultConnection);
var qtype = item.GetType();
if (qtype.BaseType.BaseType != null)
{
if ((isNew && qtype.BaseType.Name == typeof(ModelBase).Name) | qtype.BaseType.BaseType.Name == typeof(ModelBase).Name)
{
Thread.Sleep(500);
//collect data
var element = (ModelBase)item;
element.BuildMetaData(DataRequestType.CurrentItem);
var records = ModelBase.MetaData;
ModelBase.MetaData = new List<ModelRecord> { };
if (records == null) return;
foreach (ModelRecord r in records)
{
if (r!=null)
{
var jsr = new JavaScriptSerializer();
//object meta = r;
object rdata = r.Data;
var type = rdata.GetType();
var token = type.BaseType.Name;
List<string> include = r.Include;
// Cycle-through clieanup of models to be encoded into Json Data.
// this helper eliminates infinate relations by including records specified
// by a list of strings
if (include.Where(x => x.Contains("CreatedByUser")).Count() == 0)
include.Add("CreatedByUser");
if (include.Where(x => x.Contains("UpdatedByUser")).Count() == 0)
include.Add("UpdatedByUser");
var data = ClassCloner.CollectData(rdata, include);
List<string> tags = ClassCloner.CollectTags(data);
string _tags = "";
tags.ForEach((xtm) =>
{
_tags += xtm + ',';
});
var json = jsr.Serialize(data);
int id = 0;
//get identity
foreach (var prop in type.GetProperties())
{
if (id == 0)
{
foreach (var cp in prop.CustomAttributes)
{
if (cp.AttributeType.Name == "KeyAttribute")
{
var _id = ((Dictionary<string, object>)data)[prop.Name];
id = (int)_id;
break;
}
}
}
else { break; }
}
var query = dm.JsonObjectRepository.GetAll();
var key = "_" + token;
var _data = (Dictionary<string, object>)data;
var ExistingMetaData = (from x in query where x.SourceKey == key && x.SourceId == id select x).FirstOrDefault();
if (ExistingMetaData != null)
{
if (_data.ContainsKey("DateUpdated")) ExistingMetaData.Date = (DateTime)_data["DateUpdated"];
ExistingMetaData.SourceData = data;
ExistingMetaData.Encode();
ExistingMetaData.Active = active;
ExistingMetaData.SearchTags = _tags;
dm.JsonObjectRepository.Update(ExistingMetaData);
}
else
{
var newData = new JsonObject
{
Active = true,
Date = (DateTime)_data["DateUpdated"],
SourceData = data,
SourceId = id,
SourceKey = key,
SearchTags = _tags,
TargetKey = "GlobalSearchMetaData"
};
newData.Encode();
dm.JsonObjectRepository.Create(newData);
}
}
}
}
}
}
}
void BuildMetaData(object dataRecord, bool active, bool isNew)
{
new Thread((item) => { BuildMetaDataNoThread(item, active, isNew); }).Start(dataRecord);
}
I have following service method
public async Task<IResultList<IEnrichedContentEntity>> QueryAsync(Context context, string schemaIdOrName, Q q)
{
Guard.NotNull(context, nameof(context));
if (q == null)
{
return EmptyContents;
}
var schema = await GetSchemaOrThrowAsync(context, schemaIdOrName);
var permissionReadOwn = Permissions.ForApp(Permissions.AppContentReadOwn, context.App.Name, schemaIdOrName);
if (context.Permissions.Allows(permissionReadOwn))
{
q.CreatedBy = context.User.Token();
}
using (Profiler.TraceMethod<ContentQueryService>())
{
q = await queryParser.ParseAsync(context, q, schema);
var contents = await contentRepository.QueryAsync(context.App, schema, q, context.Scope());
if (q.Ids != null && q.Ids.Count > 0)
{
contents = contents.SortSet(x => x.Id, q.Ids);
}
return await TransformAsync(context, contents);
}
}
q.CreatedBy must set value if permission is correct.
How can I test if q.CreatedBy is not empty and has correct value.
I implemented following test, but no idea how check this params?
public async Task QueryAll_should_return_own_user_contents(int isFrontend, int unpublished, SearchScope scope)
{
var ctx = CreateContextWithOwnReadPermission(isFrontend: isFrontend == 1, allowSchema: true)
.WithUnpublished(unpublished == 1);
var content = CreateContent(contentId);
var q = Q.Empty.WithReference(DomainId.NewGuid());
A.CallTo(() => contentRepository.QueryAsync(ctx.App, schema, q, scope))
.Returns(ResultList.CreateFrom(5, content));
//A.CallTo(() => contentRepository.QueryAsync(ctx.App, schema, A<Q>.That.Matches(x => x.CreatedBy == null), scope))
// .MustHaveHappened();
//A.CallTo(() => contentRepository.QueryAsync(ctx.App, schema, A<Q>.That.Matches(x => x.CreatedBy == ctx.User.Token()), scope))
// .MustHaveHappened();
//q.CreatedBy = ctx.User.Token();
var result = await sut.QueryAsync(ctx, schemaId.Name, q);
Assert.Equal(contentData, result[0].Data);
Assert.Equal(contentId, result[0].Id);
Assert.Equal(5, result.Total);
}
Just trying to do normal query on ef but getting below error message
"A second operation started on this context before a previous asynchronous operation completed"
I am using await for all aync call but not sure what could be causing this issue.
here' code
var sids = await context.Sites.Where(s => slist.Contains(s.JVSiteID)).ToListAsync();
var header = await context.GenericCsvHeaders.FirstOrDefaultAsync(x => x.Header == csvh) ?? new GenericCsvHeader { Header = csvh };
context.Entry<GenericCsvHeader>(header).State = (header.GenericCsvHeaderID == 0) ? EntityState.Added : EntityState.Unchanged;
var sa = await context.SAs.Where(x => x.StatusID == Data.Enum.Status.Active && mapkeys.Contains(x.SAName)).Select(x => new { x.SAName, x.SACode, x.SAID }).ToListAsync();
if (sa.Count > 0)
sasitelist = await context.Site_SA.Where(x => x.StatusID == Data.Enum.Status.Active && siteids.Contains(x.SiteID ?? 0)).ToListAsync();
var az = await context.Azimuths.Where(x => x.StatusID == Data.Enum.Status.Active && mapkeys.Contains(x.AzimuthName)).Select(x => new { x.AzimuthName, x.AzimuthID }).ToListAsync();
if (az.Count > 0)
azsitelist = await context.Site_Azimuth.Where(x => x.StatusID == Data.Enum.Status.Active && siteids.Contains(x.SiteID ?? 0)).ToListAsync();
var rows = new List<dynamic>(); //getting this list from csv file via csvHelper
foreach (var r in rows)
{
var s = sids.FirstOrDefault(x => x.JVSiteID == (((IDictionary<String, Object>)r)[siteid]).ToString()) ?? new Site();
UpdateSite(s, r, map);
}
private async void UpdateSite(Site site, dynamic csvSite, IDictionary<string, string> map)
{
context.Entry(site).State = (site.StateID == 0) ? EntityState.Added : EntityState.Modified;
site.SiteForAuditTrail = site;
if (map.ContainsKey("SiteName") && !String.IsNullOrWhiteSpace(GetStringOfDynamic(map,csvSite,"SiteName")))
site.SiteName = GetStringOfDynamic(map,csvSite, "SiteName");
if (map.ContainsKey("State") && !String.IsNullOrWhiteSpace(GetStringOfDynamic(map,csvSite, "State")))
{
//getting exception at below line
var state = (await GetRefTypeList<State>(x => x.StateCode == GetStringOfDynamic(map,csvSite, "State"))) ?? new State { StateCode = GetStringOfDynamic(map,csvSite, "State") };
context.Entry(state).State = (state.StateID == 0) ? EntityState.Added : EntityState.Unchanged;
site.State = state;
state.SiteForAuditTrail = site;
}
}
private async Task<T> GetRefTypeList<T>(Func<T, bool> expression) where T : EntityBase
{
if (!refTypes.ContainsKey(typeof(T).Name))
refTypes[typeof(T).Name] = (await context.Set<T>().Where(x => x.StatusID == Data.Enum.Status.Active).ToListAsync());
return (refTypes[typeof(T).Name] as List<T>)?.FirstOrDefault(expression);
}
private string GetStringOfDynamic(IDictionary<string, string> map,dynamic obj, string propertyName)
{
if (((IDictionary<String, Object>)obj).ContainsKey(map[propertyName]))
return (((IDictionary<String, Object>)obj)[map[propertyName]]??"").ToString();
return "";
}
found problem, was missing await when calling UpdateSite
foreach (var r in rows)
{
var s = sids.FirstOrDefault(x => x.JVSiteID == (((IDictionary<String, Object>)r)[siteid]).ToString()) ?? new Site();
**await** UpdateSite(s, r, map);
}
You are having a race condition here. While you are using await you have other code executing potentially before the variable sids, header, sa and az, have been returned.
You should refactor your code so that the remaining code is not executed until these variables are returned. You can do this by using a task and then using the extension WhenAll which will ensure each await has been completed before proceeding. Here is a link to MS docs on Task and WhenAll implementation
I would like to implement an async function in converting the object to another object then in saving to the database.
public List<Order> GetOrdersFromTradeGeckoCount()
{
string orderLimit = base.StorePlugin.Store.OrderLimit.HasValue ? base.StorePlugin.Store.OrderLimit.Value.ToString() : "250";
string filters = string.Format("?status=finalized&limit={0}", orderLimit);
HttpResponseMessage response = _requestHelper.GetHttpResponse("orders" + filters);
var tgOrders = GetOrdersResponse(response);
//Async Convert and Save Order
ConvertToORouterOrdersAsync(tgOrders);
return ConvertToORouterOrdersCount(tgOrders);
}
I would like this method ConvertToORouterOrdersAsync(tgOrders); will run in the background and will return the Count of Orders from this ConvertToORouterOrdersCount(tgOrders) before the conversion is done.
Please help me to change the implementation to asynchronous.
public async void ConvertToORouterOrdersAsync(List<TGOrder> tgOrders)
{
var orderMgr = new OrderDAC();
var orders = new List<Order>(tgOrders.Count());
foreach (TGOrder tgOrder in tgOrders)
{
try
{
var order = new Order();
var orderId = TryConvertInt64(CleanUpOrderId(tgOrder.order_number));
if (orderId == null) continue;
var tempOrderId = string.Format("{0}{1}", base.StoreId, orderId.Value);
order.OrderId = TryConvertInt64(tempOrderId).Value;
order.StoreOrderId = tgOrder.id.ToString();
order.WarehouseOrderId = tgOrder.order_number;
var orderFromDb = orderMgr.GetOrder(order.OrderId, base.StoreId);
if (orderFromDb != null) continue; // make sure we only import new order(i.e. doesn't exists in database)
// shipping address
var tgShippingAddress = GetAddress(tgOrder.shipping_address_id);
if (tgShippingAddress == null) continue;
order.ShipFirstName = tgShippingAddress.first_name;
order.ShipLastName = tgShippingAddress.last_name;
order.ShipCompanyName = tgShippingAddress.company_name;
order.ShipAddress1 = tgShippingAddress.address1;
order.ShipAddress2 = tgShippingAddress.address2;
order.ShipCity = tgShippingAddress.suburb;
order.ShipState = tgShippingAddress.state;
order.ShipPostalCode = tgShippingAddress.zip_code;
order.ShipCountry = tgShippingAddress.country;
order.ShipPhoneNumber = tgShippingAddress.phone_number;
order.CustomerEmail = tgOrder.email;
// billing address
var tgBillingAddress = GetAddress(tgOrder.billing_address_id);
if (tgBillingAddress == null) continue;
// line items
var lineItems = GetOrderLineItems(tgOrder.id);
foreach (TGOrderLineItem lineItem in lineItems)
{
var ol = new OrderLine();
if (lineItem.variant_id.HasValue)
{
var variant = GetVariant(lineItem.variant_id.Value);
if (variant == null) continue;
ol.ProductName = variant.product_name;
ol.SKU = variant.sku;
ol.ThreePLSKU = ol.SKU;
ol.Qty = Convert.ToInt16(TryGetDecimal(lineItem.quantity));
ol.OrderId = order.OrderId;
ol.Price = TryGetDecimal(lineItem.price);
ol.SubTotal = (ol.Qty * ol.Price);
ol.StoreOrderLineId = Convert.ToString(lineItem.id);
order.OrderLines.Add(ol);
}
}
var validator = new Validator(base.Task);
if (validator.IsValidOrder(order))
{
orderMgr.Add(order);
}
}
catch (Exception ex)
{
AppendError(ex.Message);
}
}
}
To really have a advantage of the async and await the underlying calls should have async versions, for example the database calls should be async, don't know if you use EF or just plain SqlCommand but both have async versions of their calls.
Other calls that can be async is HTTP calls.
I have edited youre code with the assumption you are able to convert the underlying code to async.
public async Task<List<Order> GetOrdersFromTradeGeckoCount()
{
string orderLimit = base.StorePlugin.Store.OrderLimit.HasValue ? base.StorePlugin.Store.OrderLimit.Value.ToString() : "250";
string filters = string.Format("?status=finalized&limit={0}", orderLimit);
HttpResponseMessage response = await _requestHelper.GetHttpResponseAsync("orders" + filters).ConfigureAwait(false);
var tgOrders = GetOrdersResponse(response);
//Async Convert and Save Order
await ConvertToORouterOrdersAsync(tgOrders).ConfigureAwait(false);
return await ConvertToORouterOrdersCountAsync(tgOrders).ConfigureAwait(false);
}
public async Task ConvertToORouterOrdersAsync(List<TGOrder> tgOrders)
{
var orderMgr = new OrderDAC();
var orders = new List<Order>(tgOrders.Count());
foreach (TGOrder tgOrder in tgOrders)
{
try
{
var order = new Order();
var orderId = TryConvertInt64(CleanUpOrderId(tgOrder.order_number));
if (orderId == null) continue;
var tempOrderId = string.Format("{0}{1}", base.StoreId, orderId.Value);
order.OrderId = TryConvertInt64(tempOrderId).Value;
order.StoreOrderId = tgOrder.id.ToString();
order.WarehouseOrderId = tgOrder.order_number;
var orderFromDb = await orderMgr.GetOrderAsync(order.OrderId, base.StoreId).ConfigureAwait(false);
if (orderFromDb != null) continue; // make sure we only import new order(i.e. doesn't exists in database)
// shipping address
var tgShippingAddress = GetAddress(tgOrder.shipping_address_id);
if (tgShippingAddress == null) continue;
order.ShipFirstName = tgShippingAddress.first_name;
order.ShipLastName = tgShippingAddress.last_name;
order.ShipCompanyName = tgShippingAddress.company_name;
order.ShipAddress1 = tgShippingAddress.address1;
order.ShipAddress2 = tgShippingAddress.address2;
order.ShipCity = tgShippingAddress.suburb;
order.ShipState = tgShippingAddress.state;
order.ShipPostalCode = tgShippingAddress.zip_code;
order.ShipCountry = tgShippingAddress.country;
order.ShipPhoneNumber = tgShippingAddress.phone_number;
order.CustomerEmail = tgOrder.email;
// billing address
var tgBillingAddress = GetAddress(tgOrder.billing_address_id);
if (tgBillingAddress == null) continue;
// line items
var lineItems = GetOrderLineItems(tgOrder.id);
foreach (TGOrderLineItem lineItem in lineItems)
{
var ol = new OrderLine();
if (lineItem.variant_id.HasValue)
{
var variant = GetVariant(lineItem.variant_id.Value);
if (variant == null) continue;
ol.ProductName = variant.product_name;
ol.SKU = variant.sku;
ol.ThreePLSKU = ol.SKU;
ol.Qty = Convert.ToInt16(TryGetDecimal(lineItem.quantity));
ol.OrderId = order.OrderId;
ol.Price = TryGetDecimal(lineItem.price);
ol.SubTotal = (ol.Qty * ol.Price);
ol.StoreOrderLineId = Convert.ToString(lineItem.id);
order.OrderLines.Add(ol);
}
}
var validator = new Validator(base.Task);
if (validator.IsValidOrder(order))
{
await orderMgr.AddAsync(order).ConfigureAwait(false);
}
}
catch (Exception ex)
{
AppendError(ex.Message);
}
}
}
Or if you just want to run the code in the background you can also just wrap it in a Task.Run
public async Task<List<Order> GetOrdersFromTradeGeckoCount()
{
string orderLimit = base.StorePlugin.Store.OrderLimit.HasValue ? base.StorePlugin.Store.OrderLimit.Value.ToString() : "250";
string filters = string.Format("?status=finalized&limit={0}", orderLimit);
HttpResponseMessage response = _requestHelper.GetHttpResponse("orders" + filters);
var tgOrders = GetOrdersResponse(response);
//Async Convert and Save Order
await ConvertToORouterOrdersAsync(tgOrders).ConfigureAwait(false);
return ConvertToORouterOrdersCount(tgOrders);
}
public Task ConvertToORouterOrdersAsync(List<TGOrder> tgOrders)
{
return Task.Run(() =>
{
var orderMgr = new OrderDAC();
var orders = new List<Order>(tgOrders.Count());
foreach (TGOrder tgOrder in tgOrders)
{
try
{
var order = new Order();
var orderId = TryConvertInt64(CleanUpOrderId(tgOrder.order_number));
if (orderId == null) continue;
var tempOrderId = string.Format("{0}{1}", base.StoreId, orderId.Value);
order.OrderId = TryConvertInt64(tempOrderId).Value;
order.StoreOrderId = tgOrder.id.ToString();
order.WarehouseOrderId = tgOrder.order_number;
var orderFromDb = await orderMgr.GetOrder(order.OrderId, base.StoreId);
if (orderFromDb != null) continue; // make sure we only import new order(i.e. doesn't exists in database)
// shipping address
var tgShippingAddress = GetAddress(tgOrder.shipping_address_id);
if (tgShippingAddress == null) continue;
order.ShipFirstName = tgShippingAddress.first_name;
order.ShipLastName = tgShippingAddress.last_name;
order.ShipCompanyName = tgShippingAddress.company_name;
order.ShipAddress1 = tgShippingAddress.address1;
order.ShipAddress2 = tgShippingAddress.address2;
order.ShipCity = tgShippingAddress.suburb;
order.ShipState = tgShippingAddress.state;
order.ShipPostalCode = tgShippingAddress.zip_code;
order.ShipCountry = tgShippingAddress.country;
order.ShipPhoneNumber = tgShippingAddress.phone_number;
order.CustomerEmail = tgOrder.email;
// billing address
var tgBillingAddress = GetAddress(tgOrder.billing_address_id);
if (tgBillingAddress == null) continue;
// line items
var lineItems = GetOrderLineItems(tgOrder.id);
foreach (TGOrderLineItem lineItem in lineItems)
{
var ol = new OrderLine();
if (lineItem.variant_id.HasValue)
{
var variant = GetVariant(lineItem.variant_id.Value);
if (variant == null) continue;
ol.ProductName = variant.product_name;
ol.SKU = variant.sku;
ol.ThreePLSKU = ol.SKU;
ol.Qty = Convert.ToInt16(TryGetDecimal(lineItem.quantity));
ol.OrderId = order.OrderId;
ol.Price = TryGetDecimal(lineItem.price);
ol.SubTotal = (ol.Qty * ol.Price);
ol.StoreOrderLineId = Convert.ToString(lineItem.id);
order.OrderLines.Add(ol);
}
}
var validator = new Validator(base.Task);
if (validator.IsValidOrder(order))
{
orderMgr.Add(order);
}
}
catch (Exception ex)
{
AppendError(ex.Message);
}
}
});
}
While using Dapper for multiple Query:
var result = sqlConnection.QueryMultiple(query, Parameters, commandType: commandType);
How can i get the table count returned from query? It has two overloaded implementation of .Read() method, which each time called, moves to next available result set (No result.Count() property). Eventually i want to put that number in a loop to iterate as many time as number of tables returned from query.
var reader = this.DbConnection.QueryMultipleAsync(sql, Params, commandType: CommandType.StoredProcedure).Result;
if(reader.IsConsumed == false)
{
DeviceTypeReport = reader?.ReadAsync<dynamic>().Result;
}
This is probably what you are looking for hope it helps.
This is probably what you are looking for hope it helps.
List<dynamic> data = new List<dynamic>();
while (reader.IsConsumed == false)
{
data.Add(await reader?.ReadAsync<dynamic>());
}
int totalRecordSet = data.Count;
public List NotificationExecuteMultiple(OutdoorRequest objreq, IConfiguration configuration)
{
var lst = new List<dynamic>();
using (DbConnection connection = new MySqlConnection(configuration.GetConnectionString("SquareHrConn")))
{
using (var dr = connection.QueryMultiple(ProcedureName, GetParamenter(objreq), commandType: CommandType.StoredProcedure))
{
while (dr.IsConsumed == false)
{
lst.Add(dr.Read());
}
}
}
return lst;
}
Consider the follwoing method to cover all cases
protected List<object> ExecuteMultiQuery<A, B, C, D, E, F, G, H, I, J>(string procedureName, DynamicParameters param = null)
{
List<object> result = new List<object>();
using (var connection = new SqlConnection(ConnectionManager.ConnectionString))
{
try
{
connection.Open();
using (var multi = connection.QueryMultiple(procedureName, param, commandType: CommandType.StoredProcedure, commandTimeout: 120))
{
var varA = multi.Read<A>();
if (varA != null) { result.Add(varA.ToList()); }
var varB = multi.Read<B>();
if (varB != null) { result.Add(varB.ToList()); }
var varC = multi.Read<C>();
if (varC != null) { result.Add(varC.ToList()); }
var varD = multi.Read<D>();
if (varD != null) { result.Add(varD.ToList()); }
var varE = multi.Read<E>();
if (varE != null) { result.Add(varE.ToList()); }
var varF = multi.Read<F>();
if (varF != null) { result.Add(varF.ToList()); }
var varG = multi.Read<G>();
if (varG != null) { result.Add(varG.ToList()); }
var varH = multi.Read<H>();
if (varH != null) { result.Add(varH.ToList()); }
var varI = multi.Read<I>();
if (varI != null) { result.Add(varI.ToList()); }
var varJ = multi.Read<J>();
if (varJ != null) { result.Add(varJ.ToList()); }
//if (varA != null) { result.Add(varA.ToList()); }
//if (resultSets > 1) { result.Add(multi.Read<B>().ToList()); }
//if (resultSets > 2) { result.Add(multi.Read<C>().ToList()); }
//if (resultSets > 3) { result.Add(multi.Read<D>().ToList()); }
//if (resultSets > 4) { result.Add(multi.Read<E>().ToList()); }
//if (resultSets > 5) { result.Add(multi.Read<F>().ToList()); }
//if (resultSets > 6) { result.Add(multi.Read<G>().ToList()); }
//if (resultSets > 7) { result.Add(multi.Read<H>().ToList()); }
//if (resultSets > 8) { result.Add(multi.Read<I>().ToList()); }
//if (resultSets > 9) { result.Add(multi.Read<J>().ToList()); }
return result;
}
}
catch (System.Exception e)
{
string message = e.Message;
}
}
return result;
}