I have created the following class to make all my queries paged, but i don't know how to make the final query asynchronous, is it possible with SqlKata?
public class PagedList<T> : List<T>
{
public int CurrentPage { get; set; }
public int TotalPages { get; set; }
public int PageSize { get; set; }
public int TotalCount { get; set; }
public PagedList(List<T> items, int totalCount, int pageNumber, int pageSize)
{
TotalCount = totalCount;
PageSize = pageSize;
CurrentPage = pageNumber;
TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
this.AddRange(items);
}
public static async Task<PagedList<T>> CreateAsync(Query query, int pageNumber, int pageSize)
{
var count = query.AsCount();
var items = query.Skip((pageNumber - 1) * pageSize).Take(pageSize).???;
}
}
So after "Take(pageSize)" in the last query I see no SelectAsync or GetAsync. Any idea how to do this?
Related
i am creating Api to get my store quantity according store id and date from to but i had no result code below
please can any one help me in this issue.
public class StoresQtyDto
{
public int ID { get; set; }
public int? ItemID { get; set; }
public string ItemLookupCode { get; set; }
public int CategoryID { get; set; }
public int DepartmentID { get; set; }
public string itemDescription { get; set; }
public string SubDescription3 { get; set; }
public decimal? SnapShotPrice { get; set; }
public double? SnapShotQuantity { get; set; }
public int StoreId { get; set; }
public string barcode { get; set; }
public DateTime lastupdated { get; set; }
}
public interface IStoresQtyRepository
{
Task<StoresQty[]> GetItemsByDate(DateTime fromDate, DateTime toDate, int storeId);
}
public class StoresQtyRepository : IStoresQtyRepository
{
private readonly ApiSiteDbContext _db;
private readonly ILogger<StoresQtyRepository> _logger;
public StoresQtyRepository(ApiSiteDbContext db, ILogger<StoresQtyRepository> logger)
{
_db = db;
_logger = logger;
}
public async Task<StoresQty[]> GetItemsByDate(DateTime fromDate, DateTime toDate, int storeId)
{
_logger.LogInformation($"Getting Allt Stores Items with Store ID {storeId} from Date {fromDate} to date {toDate}");
var query = _db.storesQties.Where(s => s.lastupdated == fromDate && toDate == DateTime.Now && s.StoreId == storeId);
return await query.ToArrayAsync();
}
*******************Controller
private readonly IStoresQtyRepository _storesQty;
private readonly IMapper _mapper;
public StoresQtiesController(IStoresQtyRepository storesQty, IMapper mapper)
{
_storesQty = storesQty;
_mapper = mapper;
}
}
[HttpGet("StoresQties")]
public async Task<ActionResult<StoresQtyDto[]>> GetItemsByDate(DateTime fromDate, DateTime toDate, int storeId)
{
try
{
if (ModelState.IsValid)
{
var results = await _storesQty.GetItemsByDate(fromDate, toDate, storeId);
if (!results.Any())
return NotFound($"No Items found in store with id {storeId} and date from {fromDate}");
var mappedEntities = _mapper.Map<StoresQtyDto[]>(results);
return Ok(mappedEntities);
}
}
catch (Exception)
{
return this.StatusCode(StatusCodes.Status500InternalServerError, "Database Failure");
}
return BadRequest();
}
after i run it in Postman its return not found , but date and storeId already exist in data base
I'm trying to get sum of all items of cars. But i'm just getting sum of each items, which you can see here Link
So how can I get sum of all items, like the sum is (4), instead of getting each items?
Controller:
public ActionResult Home()
{
var model = new CompositeModel();
model.CountCars = getCountOfCars();
return View(model);
}
private IEnumerable<CountCarsrCountView> getCountOfCars()
{
var countCars = this.Data.Cars.All()
.Select(t => new CountCarsrCountView
{
counter = t.Cars.Count()
});
return countCars ;
}
ViewModel
public class CountCarsViewModel
{
public int counter { get; set; }
}
CompositeModel
public class CompositeModel
{
public IEnumerable<CountCarsViewModel> CountCars { get; set; }
}
View
#model CompositeModel
<div class="container">
#for (int i = 0; i < Model.CountCarsViewModel.Count(); i++)
{
var cars = Model.CountCarsViewModel.ElementAt(i);
<p>#cars.counter</p>
}
</div>
Car model:
public class Car
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Price { get; set; }
public virtual Category Category { get; set; }
public int CategoryId { get; set; }
public int FilePathId { get; set; }
public string FileName { get; set; }
public string UserId { get; set; }
public virtual User Users { get; set; }
}
You can use Linq as so:
public class MyItem
{
public int MyCount { get; set; }
}
public List<MyItem> AllItems { get; set; }
In this example if you want the count of all items in the list you would do this:
var count = AllItems.Count();
If you wanted to sum the Counts of all items in the list you would do this:
var count2 = AllItems.Sum(a => a.MyCount);
Example:
AllItems = new List<UserQuery.MyItem>()
{
new MyItem(){ MyCount = 3 },
new MyItem(){ MyCount = 4 },
};
var count = AllItems.Count(); // This would be 2
var count2 = AllItems.Sum(a => a.MyCount); // This would be 7
public class OrderDTO
{
public string ClientName { get; set; }
public ICollection<OrderDetailDTO> Details { get; set; }
}
public class Order
{
public string ClientName { get; set; }
public ICollection<OrderDetail> Details { get; set; }
}
public class OrderDetailDTO
{
public int Quantity { get; set; }
public string ProductName { get; set; }
}
public class OrderDetail
{
public int OrderId { get; set; }
public int Quantity { get; set; }
public string ProductName { get; set; }
}
Let's say there are 4 OrderDetailDTO, I want to have the mapped OrderDetail instances with auto-incremented integer values. What I am doing now is post-process the mapped instance.
var mappedOrder = Mapper.Map<OrderDTO, Order>(orderDto);
var orderId = 1;
foreach (OrderDetail detail in mappedOrder.Details)
{
detail.OrderId = orderId++;
}
How can I configure the mapping options, so that the mapped ICollection<OrderDetail> contains 4 OrderDetail instances with OrderId as 1, 2, 3, 4?
You could configure AutoMapper to do this with AfterMap:
Mapper.CreateMap<OrderDTO, Order>()
.AfterMap((src, dest) =>
{
int orderId = 1;
foreach (OrderDetail detail in dest.Details)
{
detail.OrderId = orderId++;
}
});
I don't think there's really a "cleaner" way to do it using AutoMapper.
I use the following method which is much simpler and can be written in a base class or an extension method. The example here uses Generics but can be easily transformed
protected virtual IEnumerable<T> ConvertCsvLines(IEnumerable<TV> lines)
{
var lineNumber = 0;
return lines.Select(x =>
{
var retVal = Mapper.Map<TV, T>(x);
retVal.LineNumber = lineNumber++;
return retVal;
});
}
I'm getting this wierd error when I try this code:
class SomeClass
{
public decimal ClientCode { get; set; }
public DateTime Date { get; set; }
public override int GetHashCode()
{
int sum = 0;
foreach (var p in GetType().GetProperties())
{
var method = p.GetType().GetMethod("GetHashCode");
var value = p.GetValue(this, null);
sum += (int)(method.Invoke(value, null)); // <-- HERE!
}
return sum;
}
}
What's wrong with that? I'm iterating through properties cause this code will be emitted.
I must get GetHashCode from object, not from PropertyType
public class SomeClass
{
public decimal ClientCode { get; set; }
public DateTime Date { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public byte B { get; set; }
public override int GetHashCode()
{
int sum = 0;
foreach (var p in GetType().GetProperties())
{
var method = typeof(object).GetMethod("GetHashCode");
var value = p.GetValue(this, null);
if (value != null)
sum += (int)(method.Invoke(value, null));
}
return sum;
}
}
public ActionResult Index()
{
testEntities6 devicesEntities = new testEntities6();
List<DevicesModel> devicesModel = new List<DevicesModel>();
var device_query = from d in devicesEntities.device
join dt in devicesEntities.devicetype on d.DeviceTypeId equals dt.Id
join l in devicesEntities.location on d.Id equals l.DeviceId
join loc in devicesEntities.locationname on l.LocationNameId equals loc.Id
where l.DeviceId == d.Id
select new {
//devices
d.Id,
d.DeviceTypeId,
d.SerialNumber,
d.FirmwareRev,
d.ProductionDate,
d.ReparationDate,
d.DateOfLastCalibration,
d.DateOfLastCalibrationCheck,
d.CalCertificateFile,
d.Notes,
d.TestReportFile,
d.WarrantyFile,
d.CertificateOfOriginFile,
d.QCPermissionFile,
d.Reserved,
d.ReservedFor,
d.Weight,
d.Price,
d.SoftwareVersion,
//devicetype
dt.Name,
dt.ArticleNumber,
dt.Type,
//location
l.StartDate, //AS LastStartDate,
l.LocationNameId,
//locationname
Loc_name = loc.Name //AS CarrentLocation
};
foreach (var dv in device_query) {
devicesModel.Add(new DevicesModel(
//device
DeviceTypeId = dv.DeviceTypeId,
/*Why I have this error: The name 'DeviceTypeId' does not exist in the current context*/
...
));
}
return View(devicesModel);
}
Model:
public class DevicesModel
{
//device
public int deviceTypeId;
public int id;
public int serialNumber;
public string firmwareRev;
public DateTime productionDate;
public DateTime reparationDate;
public DateTime dateOfLastCalibration;
public DateTime dateOfLastCalibrationCheck;
public int calCertificateFile;
public string notes;
public int testReportFile;
public int warrantyFile;
public int certificateOfOriginFile;
public int qCPermissionFile;
public int BReserved;
public string reservedFor;
public double weight;
public int price;
public string softwareVersion;
//devicetype
public string name;
public string qrticleNumber;
public string type;
//location
public DateTime startDate;
public int locationNameId;
//locationname
public string loc_name;
public DevicesModel(){}
//device
public int DeviceTypeId{get;set;}
public int Id { get; set; }
public int SerialNumber { get; set; }
public string FirmwareRev { get; set; }
public DateTime ProductionDate { get; set; }
public DateTime ReparationDate { get; set; }
public DateTime DateOfLastCalibration { get; set; }
public DateTime DateOfLastCalibrationCheck { get; set; }
public int CalCertificateFile { get; set; }
public string Notes { get; set; }
public int TestReportFile { get; set; }
public int WarrantyFile { get; set; }
public int CertificateOfOriginFile { get; set; }
public int QCPermissionFile { get; set; }
public int bReserved { get; set; }
public string ReservedFor { get; set; }
public double Weight { get; set; }
public int Price { get; set; }
public string SoftwareVersion { get; set; }
//devicetype
public string Name { get; set; }
public string ArticleNumber { get; set; }
public string Type { get; set; }
//location
public DateTime StartDate { get; set; }
public int LocationNameId { get; set; }
//locationname
public string Loc_name { get; set; }
}
Its because you're creating an anonymous object in your linq "Select" clause. I think you want to create an instance of your DevicesModel class, e.g.
...
where l.DeviceId == d.Id
select new DevicesModel {
//devices
Id = d.Id,
...
I think you intend to use curly brackets instead of round brackets.
new DevicesModel
{
//device
DeviceTypeId = dv.DeviceTypeId,
...
}
or are you trying to use named arguments in C#4?