I create the following function to calculate total between two dates but always get null value what was wrong ?
void calcul_total_period() async {
var totalSumPeriod = (await databaseHelper.claculTotalPeriod(startDate, endDate))[0]['TOTAL']; //['$startDate''$endDate'];
print(' $totalSumPeriod');
setState(() {
somme_period = totalSumPeriod ?? 00;
somme_total_period = somme.toStringAsFixed(2);
});
}
function in db
Future claculTotalPeriod (String startDate, String endDate) async {
var totalClientperiod = await database;
var result = await totalClientperiod.rawQuery("SELECT SUM($colPrix) AS TOTAL from $clientTable WHERE $colDate BETWEEN '$startDate' AND '$endDate'");
print('$result');
return result.toList();
}
What's somme ?
void calcul_total_period() async {
var totalSumPeriod = (await databaseHelper.claculTotalPeriod(startDate, endDate))[0]['TOTAL']; //['$startDate''$endDate'];
print(' $totalSumPeriod');
setState(() {
somme_period = totalSumPeriod ?? 00;
somme_total_period = ---> somme <----.toStringAsFixed(2);
});
}
Related
I have the following entities:
Batch
Samples
SampleContainers
SampleTests
A batch contains many samples. A sample contains many SampleContainers and many SampleTests.
I am trying to make a copy of batch and insert into database.
Attempt #1: get function in repository:
return await context.Set<TEntity>().FindAsync(id);
Controller:
var coc = await repository.Get(batchId);
coc.BatchStatusId = (int)Enums.BatchStatus.InProgress;
coc.IsTemplate = false;
coc.Id = 0;
var b = await repository.Add(coc);
Here only batch object was duplicated but related samples and containers were not duplicated/inserted.
Attempt #2: I changed my Get function as follows:
public async override Task<Batch> Get(int id)
{
return await context.Set<Batch>()
.Include(p => p.Samples)
.FirstOrDefaultAsync(p => p.Id == id);
}
This time batch was duplicated but samples and containers and tests were all updated with new batchId/FK (I wanted them all to be duplicated).
Attempt #3: following this, I implemented as follows:
public async Task<int> DuplicateBatch([FromBody]int batchId)
{
try
{
var coc = await repository.Get(batchId);
coc.BatchStatusId = (int)Enums.BatchStatus.InProgress;
coc.IsTemplate = false;
coc.Id = 0;
var samples = coc.Samples.ToList();
repository.DetachEntity(coc);
var b = await repository.Add(coc);
var allSampleTests = await sampleTestRepo.GetAll();
var allSampleContainers = await sampleContainersRepo.GetAll();
var sampletests = from st in allSampleTests
join s in samples on st.SampleId equals s.Id
select st;
var sampleContainers = from sc in allSampleContainers
join s in samples on sc.SampleId equals s.Id
select sc;
sampleRepo.DetachEntities(samples);
sampleTestRepo.DetachEntities(sampletests.ToList());
sampleContainersRepo.DetachEntities(sampleContainers.ToList());
foreach (var s in samples)
{
s.BatchId = b.Id;
var sample = await sampleRepo.Add(s);
foreach (var st in sampletests)
{
st.SampleId = sample.Id;
await sampleTestRepo.Add(st);
}
foreach(var sc in sampleContainers)
{
sc.SampleId = sample.Id;
await sampleContainersRepo.Add(sc);
}
}
return 1;
}
catch (Exception ex)
{
return 0;
}
}
This time I am facing the following exception as soon as I reach Detach function:
{"The property 'Batch.Id' is part of a key and so cannot be modified
or marked as modified. To change the principal of an existing entity
with an identifying foreign key, first delete the dependent and invoke
'SaveChanges', and then associate the dependent with the new
principal."}
This is how I did it, most of it is self explanatory.
public async Task<int> DuplicateBatch([FromBody]int batchId)
{
try
{
//STEP 1: Fetch the entities
var coc2 = await repository.Get(batchId);
var samples = coc2.Samples.ToList();
var allSampleTests = await sampleTestRepo.GetAll();
var allSampleContainers = await sampleContainersRepo.GetAll();
var sampletests = samples.SelectMany(st => st.SampleTests).ToList();
var samplecontainers = samples.SelectMany(st => st.SampleContainers).ToList();
//STEP 2: Detach
var coc = repository.DetachEntity(coc2);
var samplesDetached = sampleRepo.DetachEntities(samples);
var sampleTestsDetached = sampleTestRepo.DetachEntities(sampletests);
var sampleContianersDetached = sampleContainersRepo.DetachEntities(samplecontainers);
//STEP 3: Update object
coc2.BatchStatusId = (int)Enums.BatchStatus.InProgress;
coc2.IsTemplate = false;
var b = await repository.Add(coc);
return 1;
}
catch (Exception ex)
{
return 0;
}
}
How can I execute an insertmany using sqlkata? I have a list and I want to perform an insertmany
public async Task<TimeSpan> AddBulk(List<Transaction> transactions)
{
var cols = new[] { "Id", "Name", "Description", "Quantity", "AddedOn", "ModifiedOn" };
Start = DateTime.Now;
try
{
var result = await _db.Query("Transaction").InsertAsync(cols, new[] { transactions });
}
catch(Exception ex)
{
}
TimeSpan = DateTime.Now - Start;
return TimeSpan;
}
Have you tried this:
var result = _db.Query("Transaction").AsInsert(cols, transactions);
You can convert the list of your data to List<object[]> then try to insert multiple records like this:
var cols = new[] {
"YourField1",
"YourField2" ,
"YourField3"
};
var data = new List<object[]>();
foreach (var item in YourListObject)
{
data.Add(new object[]
{
item.YourField1,
item.YourField2,
item.YourField3
});
}
var affectedRows = _db.Query(typeof(Permission).Name)
.Insert(cols, p);
This is my code. I need to get 30 class object(number of teams in NBA) with data. In both of API REQUEST there is "teamId". Using this "teamId" I need to fetch TEAM NAME from other requests. That's why I used loop, but this solution is to slow and app doesn't work good. I am looking for different solution. How can I connect this two api requests in the one object? Below the code I wrote.
String year = "2020";
http.Response response = await http.get(Uri.parse(
"https://api-nba-v1.p.rapidapi.com/standings/standard/$year?rapidapi-key=$kApiKey"));
var data = jsonDecode(response.body);
if (response.statusCode == 200) {
var standingsDetails = data['api']['standings'];
int standingsDetailsLength = standingsDetails.length;
List<StandingsModel> standingsModel = [];
for (int i = 0; i < standingsDetailsLength; i++) {
http.Response responseTeam = await http.get(Uri.parse(
"https://api-nba-v1.p.rapidapi.com/teams/teamId/${standingsDetails[0]['teamId']}?rapidapi-key=$kApiKey"));
var dataTeam = jsonDecode(responseTeam.body);
var teamDetails = dataTeam['api']['teams'];
StandingsModel standingModel = StandingsModel(
win: standingsDetails[i]['win'],
loss: standingsDetails[i]['loss'],
rank: standingsDetails[i]['conference']['rank'],
winPercentage: standingsDetails[i]['winPercentage'],
homeLoss: standingsDetails[i]['home']['loss'],
homeWin: standingsDetails[i]['home']['win'],
awayLoss: standingsDetails[i]['away']['loss'],
awayWin: standingsDetails[i]['away']['win'],
teamId: standingsDetails[i]['teamId'],
teamName: teamDetails[i]['fullName']);
standingsModel.add(standingModel);
}
standingsModel.sort((a, b) => b.winPercentage.compareTo(a.winPercentage));
print(standingsModel.length);
return (standingsModel);
} else {
print(response.statusCode);
}
}
The problem is because you are awaiting each individual API call in sequence, so you are waiting for each call to finish before you start the next one, which is going to take a long time depending on how much data you are retrieving and how many teams you have to loop through. A way around this is to split each "team name" API call into its own future and then await them all concurrently.
Future<List<StandingsModel>> getStandingsModels(String year) async {
http.Response response = await http.get(Uri.parse("https://api-nba-v1.p.rapidapi.com/standings/standard/$year?rapidapi-key=$kApiKey"));
final data = jsonDecode(response.body);
if (response.statusCode == 200) {
final standingsDetails = data['api']['standings'];
final futures = List<Future<StandingsModel>>();
for (var i = 0; i < standingsDetails.length; i++) {
final teamId = standingsDetail['teamId'];
futures.add(getTeamDetails(standingsDetails, i, teamId));
}
final standingsModels = await Future.wait(futures);
standingsModels.sort((a, b) => b.winPercentage.compareTo(a.winPercentage));
return standingsModels;
} else {
print(response.statusCode);
return [];
}
}
Future<StandingsModel> getTeamDetails(List<Map<String, dynamic>> standingsDetails, int i, String teamId) async {
http.Response response = await http.get(Uri.parse("https://api-nba-v1.p.rapidapi.com/teams/teamId/$teamId?rapidapi-key=$kApiKey"));
final data = jsonDecode(response.body);
final teamDetails = data['api']['teams'];
return StandingsModel(
win: standingsDetails[i]['win'],
loss: standingsDetails[i]['loss'],
rank: standingsDetails[i]['conference']['rank'],
winPercentage: standingsDetails[i]['winPercentage'],
homeLoss: standingsDetails[i]['home']['loss'],
homeWin: standingsDetails[i]['home']['win'],
awayLoss: standingsDetails[i]['away']['loss'],
awayWin: standingsDetails[i]['away']['win'],
teamId: standingsDetails[i]['teamId'],
teamName: teamDetails[i]['fullName'],
);
}
Hi guys can you help me understand why i keep getting a null instead of get the value.
Need to receive the saidaservicoid to be able to update. I receive the value from the view but can't update elemento. Stays null.
Thanks in advance for the help.
[Database]
[elementoRepository]
public async Task UpdateElementoSaidaServicosAsync(AddSaidasServicoViewModel model)
{
var saidaServico = await _context.SaidaServicos.FindAsync(model.SaidaServicoId);
var elemento = await _context.Elementos.FindAsync(model.ElementoId);
if (elemento == null)
{
return;
}
var updateElementoSaida = _context.Elementos.Where(e => e.Id == model.ElementoId).FirstOrDefault();
if (updateElementoSaida == null)
{
updateElementoSaida = new Elemento
{
saidaServico = saidaServico,
};
_context.Elementos.Update(updateElementoSaida);
}
else
{
int SaidaServicos = model.SaidaServicoId;
updateElementoSaida.saidaServico = saidaServico;
}
await _context.SaveChangesAsync();
return;
}
Ok. the best way that i found to solve this issue was to get the last ID.
int SaidaServicos = _context.SaidaServicos.Max(item => item.Id);
i have one webapi app in which i have one code to populate a table in the view
the controller(Home) code is
[HttpGet]
public List<Employee> GetEmployees()
{
var com = new TrainingDBEntities();
var records = from emp in com.tblEmployees
select new Employee
{
empID = emp.empID,
empName = emp.empName,
skill=emp.skill,
};
return records.ToList();
}
and in view
//show emp details
$('#btshw').click(function () {
$.ajax({
url: "/Home/GetEmployees",
success: function (result) {
console.log(result);
for (var i = 0; i < result.length; i++) {
var Row = "<tr><td>";
Row += result[i].empID + "</td><td>";
Row += result[i].empName + "</td><td>";
Row += result[i].skill + "</td><td>";
$('#emplist').append(Row);
}
$('#emplist').append("</table>");
}
,
error: function (err) {
alert(err.status.Text);
}
});
});
but after execution i got a table having 3 columns and all having values 'undefined' , i have debug the code and in the onclick event its going to the controller and it returns the correct value but data is not correct when reaching in the view(in ajax code)
You can change the result type to JsonResult:
[HttpGet]
public JsonResult GetEmployees()
{
var com = new TrainingDBEntities();
var records = from emp in com.tblEmployees
select new Employee
{
empID = emp.empID,
empName = emp.empName,
skill = emp.skill,
};
return Json(records.ToList(), JsonRequestBehavior.AllowGet);
}