Code Coming up blank every time - c#

I have this code and it is supposed to fill up the appropriate tables and it is filling the first table (Mu_Reports) one but the second table (MU_By_Machine) keeps coming up blank
using (var db = new ProductionContext())
{
var objct = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext;
objct.ExecuteStoreCommand("TRUNCATE TABLE [MU Report]");
objct.ExecuteStoreCommand("TRUNCATE TABLE [MU By Machine]");
db.SaveChanges();
var query = db.Production_Reports
.GroupBy(x => new { x.Date, x.Machine_Number, x.Shift })
.Select(x => new
{
Date = x.Key.Date,
Shift = x.Key.Shift,
MachineNum = x.Key.Machine_Number,
MU = x.Sum(i => i.Partial_MU_ * 100)
}).ToList();
foreach (var item in query)
{
var z = new MU_Report();
z.Date = System.Convert.ToDateTime(item.Date);
z.Shift = item.Shift;
z.Machine_Number = item.MachineNum;
z.MU = item.MU;
db.MU_Reports.Add(z);
db.SaveChanges();
}
var query2 = from b in db.MU_Reports
join downtime in db.Downtime_Reports on b.Shift equals downtime.Shift
where downtime.Downtime_Code.Equals("9185")
group downtime by new { b.Date, b.Shift, b.Machine_Number, b.MU } into g
select new
{
Date = g.Key.Date,
Shift = g.Key.Shift,
Machine = g.Key.Machine_Number,
MU = g.Key.MU,
No_Work_Hours = g.Sum(x => x.Total_DownTime)
};
foreach (var item in query2)
{
var y = new MU_By_Machine();
y.Date = item.Date;
y.Shift = item.Shift;
y.Machine_Number = item.Machine;
y.MU = item.MU;
y.MU_w_o_No_Work = (item.MU * 8) / (8 - item.No_Work_Hours);
db.MU_By_Machines.Add(y);
db.SaveChanges();
}
}
I don't know if it is because I cannot have query and query2 go in the same button or if I am just doing something wrong. No error occurs only MU_By_Machine appears blank. Please keep in mind I'm new to C#.

You will need to invoke .ToList() at the end of your select statement in query2 as well.

Related

Chart from multiple tables

I have three tables named Deposit, Debit and Transfer,
like
Deposit { DepositID, DepostDate, Amount}
Debit { DebitID, DebitDate, Amount}
Transfer { TransferID, TransferDate, Amount}
How can I show all three tables in one chart? I am even wondering if it is better to put those three tables into one table instead, like
Transaction {TransactionId, TransactionTypeId, TransactionDate, Amount}
where TransactiontypeId could be 1 = for Deposit, 2 for Debit and 3 for Transfer and bind this transaction table to the chart.
Let's say I have all those in one table instead and with table name Transactions then #mm8 helped me figure this out:
var result = (from pr in db.Transactions
join tr in db.TransactionType on pr.TrTypeId equals tr.TransactionTypeId
select new
{
TransactionDate = pr.TransactionDate,
TransactionType = tr.TrType,
Amount = pr.Amount
}).ToList();
chart1.DataSource = result
.GroupBy(x => x.TransactionDate.Value.Year)
.Select(g => new
{
Year = g.Key,
TransactionType = g. //////
Amount = g.Sum(y => y.Amount)
})
.ToArray();
Is is better to have a chart from one table or from multiple tables and how to do multiple.
I am aware that I have to create different series for every table like this:
var Depseries = chart1.Series.Add("Deposit");
Depseries.XValueMember = "Year";
Depseries.YValueMembers = "DepositAmount";
Depseries.Name = "Deposit";
chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
chart1.Series["Deposit"].IsValueShownAsLabel = true;
Depseries.CustomProperties = "LabelStyle=Left";
// Debit
var Debseries = chart1.Series.Add("Debit");
Debseries.XValueMember = "Year";
Debseries.YValueMembers = "DebitAmount";
Debseries.Name = "Debit";
chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
chart1.Series["Debit"].IsValueShownAsLabel = true;
Debseries.CustomProperties = "LabelStyle=Left";
// Transfer
var FDseries = chart1.Series.Add("Transfer");
FDseries.XValueMember = "Year";
FDseries.YValueMembers = "TransferAmount";
FDseries.Name = "Transfer";
chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
chart1.Series["Transfer"].IsValueShownAsLabel = true;
FDseries.CustomProperties = "LabelStyle=Left";
You could just select the data from each of the tables and then use the DataBind method to populate the series with data, e.g.:
var deposits = (from x in db.Deposits select new { x.DepositDate, x.Amount })
.ToArray()
.GroupBy(x => x.DepositDate.Year)
.Select(g => new { Year = g.Key, Amount = g.Sum(y => y.Amount) })
.ToArray();
var Depseries = chart1.Series.Add("Deposit");
Depseries.XValueMember = "Year";
Depseries.YValueMembers = "DepositAmount";
Depseries.Name = "Deposit";
chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
chart1.Series["Deposit"].IsValueShownAsLabel = true;
Depseries.CustomProperties = "LabelStyle=Left";
chart1.Series["Deposit"].Points.DataBind(deposits, "Year", "Amount", null);
var debits = (from x in db.Debits select new { x.DebitDate, x.Amount })
.ToArray()
.GroupBy(x => x.DebitDate.Year)
.Select(g => new { Year = g.Key, Amount = g.Sum(y => y.Amount) })
.ToArray();
var Debseries = chart1.Series.Add("Debit");
Debseries.XValueMember = "Year";
Debseries.YValueMembers = "DebitAmount";
Debseries.Name = "Debit";
chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
chart1.Series["Debit"].IsValueShownAsLabel = true;
Debseries.CustomProperties = "LabelStyle=Left";
chart1.Series["Debit"].Points.DataBind(debits, "Year", "Amount", null);
...

LINQ Group By Join

I'm struggling with what is a rather simple SQL select statement. How can this be translated into LINQ?
select
o.IdOrder, Date, s.suma, name, adresa
from
Clients c
join
Orders o on (c.IdClient = o.IdClient)
join
(select IdOrder, sum(price) suma
from OrderProduct
group by IdOrder) s on (o.IdOrder = s.IdOrder);
If you could point me in the right direction, I would greatly appreciate it.
This is what I have so far:
var y = from w in db.OrderProducts
group w by w.IdOrder into TotaledOrder
select new
{
IdOrder = TotaledOrder.Key,
price = TotaledOrder.Sum(s => s.price)
};
var i = 0;
var cc = new dynamic[100];
foreach (var item in y)
{
cc[i++] = db.Orders.Where(t => t.IdOrder == item.IdOrder)
.Select(p => new
{
IdOrder = item.IdOrder,
price = item.price,
}).Single();
}
Your SQL doesn't really give an idea on your underlying structure. By a guess on column names:
var result = from o in db.Orders
select new {
IDOrder = o.IDOrder,
Date = o.Date,
Suma = o.OrderProduct.Sum( op => op.Price),
Name = o.Client.Name,
Adresa = o.Client.Adresa
};
(I have no idea what you meant by the loop in your code.)

Returning List value using linq C#

Actually I want to return the data from different lists based on Date. When i'm using this i'm getting data upto #Var result but i'm unnable to return the data. The issue with this is i'm getting error #return result. I want to return the data #return result. I'm using Linq C#. Can anyone help me out?
public List<CustomerWiseMonthlySalesReportDetails> GetAllCustomerWiseMonthlySalesReportCustomer()
{
var cbsalesreeport = (from cb in db.cashbilldescriptions
join c in db.cashbills on cb.CashbillId equals c.CashbillId
join p in db.products on cb.ProductId equals p.ProductId
select new
{
Productamount = cb.Productamount,
ProductName = p.ProductDescription,
CashbillDate = c.Date
}).AsEnumerable().Select(x => new ASZ.AmoghGases.Model.CustomerWiseMonthlySalesReportDetails
{
Productdescription = x.ProductName,
Alldates = x.CashbillDate,
TotalAmount = x.Productamount
}).ToList();
var invsalesreeport = (from inv in db.invoices
join invd in db.invoicedeliverychallans on inv.InvoiceId equals invd.InvoiceId
select new
{
Productamount = invd.Total,
ProductName = invd.Productdescription,
InvoiceDate = inv.Date
}).AsEnumerable().Select(x => new ASZ.AmoghGases.Model.CustomerWiseMonthlySalesReportDetails
{
Productdescription = x.ProductName,
Alldates = x.InvoiceDate,
TotalAmount = x.Productamount
}).ToList();
var abc = cbsalesreeport.Union(invsalesreeport).ToList();
var result = (from i in abc
group i by new { Date = i.Alldates.ToString("MMM"), Product = i.Productdescription } into grp
select new { Month = grp.Key, Total = grp.Sum(i => i.TotalAmount) });
**return result;**
}
You can either convert your result to a List before returning it using return result.ToList() or make your method return an IEnumerable<CustomerWiseMonthlySalesReportDetails> instead of List.
As your result is an enumeration of anonymous types you have to convert them to your CustomerWiseMonthlySalesReportDetails-type first:
select new CustomerWiseMonthlySalesReportDetails{ Month = grp.Key, Total = grp.Sum(i => i.TotalAmount) });
Assuming your type has exactly the members returned by the select.
EDIT: So your code should look like this:
var result = (from i in abc
group i by new { Date = i.Alldates.ToString("MMM"), Product = i.Productdescription } into grp
select new CustomerWiseMonthlySalesReportDetails{ Month = grp.Key, Total = grp.Sum(i => i.TotalAmount) });
return result.ToList();
You can assume Alldates property if is date of one of groups that month of date is in right place:
var result = (from i in abc
group i by new { Date = i.Alldates.ToString("MMM"), Product = i.Productdescription }
into grp
select new CustomerWiseMonthlySalesReportDetails{
Productdescription = grp.Key.Product,
TotalAmount = grp.Sum(i => i.TotalAmount),
Alldates =grp.First(i=>i.Alldates ) })
.ToList();

This method is not supported against a materialized query result

Take a look at my code here:
public static ItemType GetItem(int id)
{
ItemType it = new ItemType();
using (var context = matrix2.matrix2core.DataAccess.Connection.GetContext())
{
var q = (from ci in context.Item
where ci.ID == id
let TemplateID = ci.TemplateID
let Groups = from x in context.CriteriaGroup
where x.TemplateID == TemplateID
select new
{
x
}
let CriteriaItems = from x in context.CriteriaItem
where Groups.Select(y => y.x.ID).Contains(x.CriteriaGroupID)
select new
{
x
}
select new
{
ci.ID,
ci.Name,
ci.CategoryID,
ci.Description,
ci.ItemValue,
TemplateID,
Groups,
CriteriaItems,
ItemValues = from x in context.ItemValue
where x.ItemID == id
select new
{
x,
CriteriaID = x.CriteriaItem.Criteria.ID
}
}).FirstOrDefault();
if (q != null)
{
it.ID = q.ID;
it.CategoryID = q.CategoryID;
it.Name = q.Name;
it.TemplateID = q.TemplateID;
it.Description = q.Description;
it.CriteriaGroups = new List<CriteriaGroupType>();
it.CriteriaItems = new List<CriteriaItemType>();
it.ItemValues = new List<ItemValueType>();
foreach (var x in q.ItemValues)
{
ItemValueType ivt = new ItemValueType();
ivt.CriteriaItemID = x.x.CriteriaItemID;
ivt.CriteriaID = x.CriteriaID;
ivt.Data = x.x.Data;
ivt.ID = x.x.ID;
ivt.ItemID = x.x.ItemID;
it.ItemValues.Add(ivt);
}
/////////error when I added the orderby clause
foreach (var x in q.Groups.OrderBy(x => x.x.SortOrder))
{
CriteriaGroupType cgt = new CriteriaGroupType();
cgt.ID = x.x.ID;
cgt.Name = !string.IsNullOrEmpty(x.x.Name) ? x.x.Name : "Group" + x.x.ID;
cgt.SortOrder = x.x.SortOrder;
cgt.TemplateID = x.x.TemplateID;
it.CriteriaGroups.Add(cgt);
}
/////////error when I added the orderby clause
foreach (var temp in q.CriteriaItems.OrderBy(x => x.x.SortOrder))
{
CriteriaItemType cit = new CriteriaItemType();
cit.ID = temp.x.ID;
cit.CriteriaGroupID = temp.x.CriteriaGroupID;
cit.GroupName = (temp.x.Name != null) ? temp.x.Name : "Group" + temp.x.ID;
cit.CriteriaID = temp.x.CriteriaID;
cit.CriteriaName = temp.x.Criteria.Name;
cit.Name = !string.IsNullOrEmpty(temp.x.Name) ? temp.x.Name : temp.x.Criteria.Name;
cit.Options = temp.x.Options;
it.CriteriaItems.Add(cit);
}
}
}
return it;
}
Instead of letting SQL handle the sorting (OrderBy) I wanted asp.net to do the sorting instead. I took the sorting out of the SQL linq query and put it on the foreach loop. When I did that I got the error. Is there a way to fix this?
You should be able to go from IQueryable to IEnumerable with a simple
var q2 = q.ToList();
What I meant of course was :
var groups = q.Groups.ToList();

How to combine 2 linq statments with groupby clause into 1

I was wondering if i can consolidate below 2 linq statments into 1 statment. I am sure it should be possible, but various attempts i am unable to manage.
var prevProvisionsBySubBook = (from provision in prevProvisions
group provision by provision.SubBook
into subBookGrouping
select
new
{
Key = subBookGrouping.Key,
Value = subBookGrouping.Sum(t => t.ProvisionUSD)
});
var currentProvisionsBySubBook
= (from provision in currentProvisions
group provision by provision.SubBook
into subBookGrouping
select new
{
Key = subBookGrouping.Key,
Value = subBookGrouping.Sum(t => t.ProvisionUSD)
});
var adjustmentChangeBySubBook
= (from current in currentProvisionsBySubBook
select new
{
Key = current.Key,
Value = current.Value
- (prevProvisionsBySubBook.Any() ? prevProvisionsBySubBook.Where(t => t.Key == current.Key).Single().Value : 0)
});
any help would be apprecaited.
You can do it like this:
var adjustmentChangeBySubBook =
from provision in
(from currentProvision in currentProvisions select new
{
currentProvision.SubBook,
CurrentUSD = currentProvision.ProvisionUSD,
PreviousUSD = 0
}).Concat
(from prevProvision in prevProvisions select new
{
prevProvision.SubBook,
CurrentUSD = 0,
PreviousUSD = prevProvision.ProvisionUSD
})
group provision by provision.SubBook into subBookGrouping select new
{
subBookGrouping.Key,
Value = subBookGrouping.Sum(t => t.CurrentUSD - t.PreviousUSD)
};

Categories