Getting parameter in ADO.Net exception when calling from angular - asp.net-mvc

I had created an API in Dot net core. When I had tested it's working well & good through postman or ARC tools. But when calling from angular, It's throwing an sqlexception like : "An SqlParameter with parameter name #TotalRows is not contained by the SqlParameterCollection."
My wonder is how it's working in postman & why not in angular call.
My API dataaccess is like below :
public List<PoDetails> GetPoDetails(PoDetails pods, string vendor_id, out int TotalRows, int Timezone)
{
List<PoDetails> posList = new List<PoDetails>();
TotalRows = 0;
try
{
con = new SqlConnection(conString);
cmd = new SqlCommand("sp_cc_get_po_details", con);
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
cmd = Util.AddConditionalParameterString(cmd, "#vendor_id", vendor_id);
cmd = Util.AddConditionalParameterString(cmd, "#sortBy", pods.sortBy);
cmd = Util.AddConditionalParameterString(cmd, "#sortDirection", pods.sortDirection);
cmd = Util.AddConditionalParameterInt(cmd, "#pageSize", pods.pageSize);
cmd = Util.AddConditionalParameterInt(cmd, "#page", pods.page);
cmd = Util.AddConditionalParameterInt(cmd, "#time_zone_offset", Timezone);
cmd.Parameters.Add(new SqlParameter("#TotalRows", SqlDbType.Int));
cmd.Parameters["#TotalRows"].Direction = ParameterDirection.Output;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
TotalRows = Convert.ToInt32(cmd.Parameters["#TotalRows"].Value);
foreach (DataRow dr in dt.Rows)
{
PoDetails posobj = new PoDetails();
posobj.vendor_name = dr["vendor_name"].ToString();
posobj.create_date = Convert.ToDateTime(dr["create_date"].ToString());
posobj.po_id = Convert.ToInt32(dr["po_id"]);
posobj.po_amount = Convert.ToInt32(dr["po_amount"]);
posobj.invoice_count = Convert.ToInt32(dr["invoicecount"]);
if (dr["utilization_amount"] != DBNull.Value)
posobj.utilization_amount = Convert.ToInt32(dr["utilization_amount"]);
else
posobj.utilization_amount = 0;
posList.Add(posobj);
}
}
catch (Exception ec)
{
throw new Exception(ec.Message);
}
return posList;
}
My procedure was like below :
ALTER PROCEDURE [dbo].[sp_cc_get_po_details]
(
#vendor_id varchar(100) = null,
#sortBy varchar(50) = NULL,
#sortDirection varchar(50) = null,
#pageSize int = NULL,
#page int = NULL,
#TotalRows int = NULL output,
#time_zone_offset int = 0
)
AS
BEGIN
SELECT Count(I.invoice_id) as invoicecount, p.po_id,p.po_amount,p.vendor_id,
DATEADD(MINUTE, #time_zone_offset, p.create_date) AS create_date ,
v.vendor_name, sum(I.invoice_amount) as utilization_amount
into #TempResults
FROM po_details p left join invoice_details I on p.po_id = I.po_id
join vendor_details v on v.vendor_id = p.vendor_id
WHERE (#vendor_id is null or #vendor_id = '' or v.vendor_id = #vendor_id)
group by p.po_id, p.po_amount, p.vendor_id, p.create_date, v.vendor_name
-- Paging Logic --
Declare #StartingRow as int = 0
Declare #FirstRow as int
Declare #LastRow as int
select #TotalRows = count(*)
from #TempResults
set #StartingRow = (#pageSize * #page) + 1
if #pageSize is not null and #page is not null begin
set #FirstRow = ((#page - 1) * #pageSize) + 1
set #LastRow = #FirstRow + (#pageSize - 1)
end else if #pageSize is not null and #StartingRow is not null begin
set #FirstRow = #StartingRow
set #LastRow = #FirstRow + (#pageSize - 1)
end else begin
set #FirstRow = 0
set #LastRow = #TotalRows
end
------
-------------------
--select #FirstRow;
--select #LastRow;
Select * from
(
Select ROW_NUMBER() over
(
order by
case when #sortBy = 'vendor_id' and #sortDirection = 'desc' then vendor_id end desc,
case when #sortBy = 'vendor_id' and #sortDirection = 'asc' then vendor_id end asc,
case when #sortBy = 'vendor_name' and #sortDirection = 'desc' then vendor_name end desc,
case when #sortBy = 'vendor_name' and #sortDirection = 'asc' then vendor_name end asc,
vendor_id
) as RowNumber, * from #TempResults
) RowData
where RowNumber between #FirstRow and #LastRow
order by RowNumber
end

Related

Optimized approach for Snowfake table search for string/list of strings from Java API

I need to search for string or list of strings Snowflake table using Java API and fetch all the matching rows and display in Angular UI. I am using dynamic SQL (like operator) to generate the query using information schema. I have created this stored procedure and its working. Do we have any better approach or any architectural patterns for this particular usecase.
Based on the search option (starts/ends with) decide the start and end character to be used with Like operator
Get all the varchar,char columns from the table by joining with information schema.
Build dynamic sql with these columns.
Build the json array based on the query result.
CREATE OR REPLACE PROCEDURE SEARCH_DATA(SCHEMA_NAME VARCHAR, TABLE_NAME VARCHAR, SEARCH_OPTION VARCHAR, KEYWORDS ARRAY)
RETURNS VARIANT
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS '
var searchStart = "";
var searchEnd = "";
if (SEARCH_OPTION == "Starts with")
{
searchEnd = "%";
}
else if (SEARCH_OPTION == "Ends with")
{
searchStart = "%";
}
else if (SEARCH_OPTION == "Contains")
{
searchStart = "%";
searchEnd = "%";
}
// Dynamically compose the SQL statement to execute.
var sqlCommand = "select c.column_name from information_schema.COLUMNS c JOIN information_schema.TABLES T ON T.table_name = c.table_name AND T.table_schema = c.table_schema WHERE T.table_schema = ''";
sqlCommand+= SCHEMA_NAME;
sqlCommand+= "'' AND T.table_name= ''";
sqlCommand+= TABLE_NAME;
sqlCommand+= "'' AND c.data_type NOT IN (''TIMESTAMP_TZ'',''BOOLEAN'',''NUMBER'') ORDER BY ordinal_position";
// Prepare statement.
var stmt = snowflake.createStatement({ sqlText: sqlCommand });
// Execute Statement
var rs = stmt.execute();
var columnArray = [];
var columnName = "";
while (rs.next())
{
columnName = rs.getColumnValue(''COLUMN_NAME'');
columnArray.push(columnName);
}
var queryPrefix = "SELECT ''dummy''"
for(var i=0; i< columnArray.length; i++)
{
queryPrefix += "," + columnArray[i];
}
queryPrefix+= " FROM " + SCHEMA_NAME + "." + TABLE_NAME;
var query = "";
for(var j=0; j< KEYWORDS.length; j++)
{
query += queryPrefix;
query += " WHERE (1=0";
for(var i=0; i< columnArray.length; i++)
{
query += " OR "+ columnArray[i] + " LIKE ''" + searchStart + KEYWORDS[j] + searchEnd + "''";
}
query += ")";
if(j < KEYWORDS.length - 1)
query += " UNION ";
}
// Prepare statement.
stmt = snowflake.createStatement({ sqlText: query });
// Execute Statement
rs = stmt.execute();
var resultArray = [];
var row_as_json = {};
while (rs.next())
{
// Put each row in a variable of type JSON.
row_as_json = {};
// For each column in the row...
for (var i=0; i< columnArray.length; i++)
{
row_as_json[columnArray[i]] = rs.getColumnValue(columnArray[i]);
}
// Add the row to the array of rows.
resultArray.push(row_as_json);
}
return resultArray;
';

Joining tables in queries google sheets

Basically I have two google sheets that look something like this:
a table where people can put in their email and select what kind of foo they are using
email
foo
example#email.com
This Foo
and then another table with information about the foo
foo name
foo type
foo boolean1
foo boolean2
This Foo
String
True
True
That Foo
Number
False
True
Other Foo
String
False
False
In a Separate Sheet I'd like to have a dashboard-like view of things wherein I would have counts of various things like number of people, how many of each type of Foo, etc
Where I'm having trouble is figuring out how to pull things like "Number of people who have selected String foos" and such
like, basically i want the google-query equivalent to (in sql)
SELECT COUNT(p.*) FROM people p JOIN info i on p.foo = i.foo_name GROUP BY i.foo_type WHERE i.foo_type = 'String'
What I would be looking for is a table that looks like this:
Data
Count
Active Roster
4
String
3
Number
1
I have also seen many solutions that have complicated formulas using VLOOKUP, INDEX, MATCH, etc.
I decided to write a user function to combine tables, or as I refer to it, de-normalize the database. I wrote the function DENORMALIZE() to support INNER, LEFT, RIGHT and FULL joins. By nesting function calls one can join unlimited tables in theory.
DENORMALIZE(range1, range2, primaryKey, foreignKey, [joinType])
Parameters:
range1, the main table as a named range, a1Notation or an array
range2, the related table as a named range, a1Notation or an array
primaryKey, the unique identifier for the main table, columns start with "1"
foreignKey, the key in the related table to join to the main table, columns start with "1"
joinType, type of join, "Inner", "Left", "Right", "Full", optional and defaults to "Inner", case insensitive
Returns: results as a two dimensional array
Result Set Example:
=QUERY(denormalize("Employees","Orders",1,3), "SELECT * WHERE Col2 = 'Davolio' AND Col8=2", FALSE)
EmpID
LastName
FirstName
OrderID
CustomerID
EmpID
OrderDate
ShipperID
1
Davolio
Nancy
10285
63
1
8/20/1996
2
1
Davolio
Nancy
10292
81
1
8/28/1996
2
1
Davolio
Nancy
10304
80
1
9/12/1996
2
Other Examples:
=denormalize("Employees","Orders",1,3)
=denormalize("Employees","Orders",1,3,"full")
=QUERY(denormalize("Employees","Orders",1,3,"left"), "SELECT * ", FALSE)
=QUERY(denormalize("Employees","Orders",1,3), "SELECT * WHERE Col2 = 'Davolio'", FALSE)
=QUERY(denormalize("Employees","Orders",1,3), "SELECT * WHERE Col2 = 'Davolio' AND Col8=2", FALSE)
=denormalize("Orders","OrderDetails",1,2)
// multiple joins
=denormalize("Employees",denormalize("Orders","OrderDetails",1,2),1,3)
=QUERY(denormalize("Employees",denormalize("Orders","OrderDetails",1,2),1,3), "SELECT *", FALSE)
=denormalize(denormalize("Employees","Orders",1,3),"OrderDetails",1,2)
=QUERY(denormalize("Employees",denormalize("Orders","OrderDetails",1,2),1,3), "SELECT *", FALSE)
=QUERY(denormalize(denormalize("Employees","Orders",1,3),"OrderDetails",4,2), "SELECT *", FALSE)
function denormalize(range1, range2, primaryKey, foreignKey, joinType) {
var i = 0;
var j = 0;
var index = -1;
var lFound = false;
var aDenorm = [];
var hashtable = [];
var aRange1 = "";
var aRange2 = "";
joinType = DefaultTo(joinType, "INNER").toUpperCase();
// the 6 lines below are used for debugging
//range1 = "Employees";
//range1 = "Employees!A2:C12";
//range2 = "Orders";
//primaryKey = 1;
//foreignKey = 3;
//joinType = "LEFT";
// Sheets starts numbering columns starting with "1", arrays are zero-based
primaryKey -= 1;
foreignKey -= 1;
// check if range is not an array
if (typeof range1 !== 'object') {
// Determine if range is a1Notation and load data into an array
if (range1.indexOf(":") !== -1) {
aRange1 = ss.getRange(range1).getValues();
} else {
aRange1 = ss.getRangeByName(range1).getValues();
}
} else {
aRange1 = range1;
}
if (typeof range2 !== 'object') {
if (range2.indexOf(":") !== -1) {
aRange2 = ss.getRange(range2).getValues();
} else {
aRange2 = ss.getRangeByName(range2).getValues();
}
} else {
aRange2 = range2;
}
// make similar structured temp arrays with NULL elements
var tArray1 = MakeArray(aRange1[0].length);
var tArray2 = MakeArray(aRange2[0].length);
var lenRange1 = aRange1.length;
var lenRange2 = aRange2.length;
hashtable = getHT(aRange1, lenRange1, primaryKey);
for(i = 0; i < lenRange2; i++) {
index = hashtable.indexOf(aRange2[i][foreignKey]);
if (index !== -1) {
aDenorm.push(aRange1[index].concat(aRange2[i]));
}
}
// add left and full no matches
if (joinType == "LEFT" || joinType == "FULL") {
for(i = 0; i < lenRange1; i++) {
//index = aDenorm.indexOf(aRange1[i][primaryKey]);
index = aScan(aDenorm, aRange1[i][primaryKey], primaryKey)
if (index == -1) {
aDenorm.push(aRange1[i].concat(tArray2));
}
}
}
// add right and full no matches
if (joinType == "RIGHT" || joinType == "FULL") {
for(i = 0; i < lenRange2; i++) {
index = aScan(aDenorm, aRange2[i][foreignKey], primaryKey)
if (index == -1) {
aDenorm.push(tArray1.concat(aRange2[i]));
}
}
}
return aDenorm;
}
function getHT(aRange, lenRange, key){
var aHashtable = [];
var i = 0;
for (i=0; i < lenRange; i++ ) {
//aHashtable.push([aRange[i][key], i]);
aHashtable.push(aRange[i][key]);
}
return aHashtable;
}
function MakeArray(length) {
var i = 0;
var retArray = [];
for (i=0; i < length; i++) {
retArray.push("");
}
return retArray;
}
function DefaultTo(valueToCheck, valueToDefault) {
return typeof valueToCheck === "undefined" ? valueToDefault : valueToCheck;
}
// Search a multi-dimensional array for a value
function aScan(aValues, searchStr, searchCol) {
var retval = -1;
var i = 0;
var aLen = aValues.length;
for (i = 0; i < aLen; i++) {
if (aValues[i][searchCol] == searchStr) {
retval = i;
break;
}
}
return retval;
}
You can make a copy of the google sheet with data and examples here:
https://docs.google.com/spreadsheets/d/1vziuF8gQcsOxTLEtlcU2cgTAYL1eIaaMTAoIrAS7mnE/edit?usp=sharing

How to update List View Model in Asp.net MVC

Hi I am facing issue in update records in MVC. I have created one list view model and in that i want to update some of the records but i am getting error. Please help me.
Here is my code:
public async Task<bool> AddPurchase(PurchaseOrderViewModel objModel, List<TableViewModel> tableListDto)
{
using (var txn = context.Database.BeginTransaction())
{
bool success = true;
try
{
PurchaseOrder purchase1 = new PurchaseOrder();
purchase1.LoginID = objModel.LoginID;
purchase1.SupplierID = objModel.SupplierID;
purchase1.SupplierName = objModel.SupplierName;
purchase1.LocationID = objModel.LocationID;
purchase1.Notes = objModel.Notes;
purchase1.Currency = objModel.Currency;
purchase1.TotalQuantity = objModel.TotalQuantity;
purchase1.TotalAmount = objModel.TotalAmount;
purchase1.TotalVolume = objModel.TotalVolume;
purchase1.TotalWeight = objModel.TotalWeight;
purchase1.TotalLandedCost = Convert.ToDecimal(objModel.TotalCost);
purchase1.TotalOtherCost = objModel.TotalOtherCost;
purchase1.Date_Of_Purchase = objModel.Date_Of_Purchase;
purchase1.Due_Date = objModel.Due_Date;
purchase1.Date_Arrived = objModel.Date_Arrived;
purchase1.Date_Departed = objModel.Date_Departed;
purchase1.CreatedBy = objModel.LoginID;
purchase1.CreatedOn = objModel.CreatedOn;
purchase1.UpdatedBy = objModel.LoginID;
purchase1.UpdatedOn = objModel.UpdatedOn;
purchase1.Status = StatusConstant.Active;
context.PurchaseOrders.Add(purchase1);
await context.SaveChangesAsync();
success = true;
int latest = purchase1.PurchaseID;
PO_Landed_Cost cost = new PO_Landed_Cost();
cost.LoginID = objModel.LoginID;
cost.PurchaseID = latest;
cost.Packaging_Costs = objModel.Packaging_Cost;
cost.Packaging_Costs_Date_Paid = objModel.Packaging_Costs_Date_Paid;
cost.Inspection_Costs = objModel.Inspection_Cost;
cost.Inspection_Costs_Date_Paid = objModel.Inspection_Costs_Date_Paid;
cost.Freight_And_Duty_Tax = objModel.Freight_Cost;
cost.Freight_And_Duty_Tax_Date_Paid = objModel.Freight_And_Duty_Tax_Date_Paid;
cost.Other_Costs = objModel.Other_Cost;
cost.Total_Landed_Cost = objModel.TotalOtherCost;
context.PO_Landed_Costs.Add(cost);
context.SaveChanges();
OrderDetail order = new OrderDetail();
PO_Landed_Cost_Spread spread1 = new PO_Landed_Cost_Spread();
List<DataDisplayViewModel> data = new List<DataDisplayViewModel>();
if (tableListDto != null)
{
foreach (var item in tableListDto)
{
//First we take all the basic things
var a = Convert.ToDecimal(item.Qty); //Quantity
var b = Convert.ToDecimal(purchase1.TotalQuantity); //Total Quantity
var e = Convert.ToDecimal(objModel.TotalOtherCost); //TotalOtherCost
var g = Convert.ToDecimal(item.Price); //Price
var j = Convert.ToDecimal(item.Volume); //Volume
var l = Convert.ToDecimal(item.Weight); //Weight
var c = Math.Round(Convert.ToDecimal((a / b) * 100), 2); //Total Percent(Quantity)
var f = Math.Round(Convert.ToDecimal(((c * e) / a) / 100), 2); // Quantity Unit Price(Indirect Cost)
var h = Math.Round(Convert.ToDecimal(f + g), 2); //Landed Cost Unit Price (Quantity)
var i = Math.Round(Convert.ToDecimal(h * a), 2); //New Total (Quantity)
var k = Math.Round(Convert.ToDecimal(a * j), 2); //Total Volume
var m = Math.Round(Convert.ToDecimal(a * l), 2); //Total Weight
DataDisplayViewModel datalist = new DataDisplayViewModel();
datalist.LoginID = objModel.LoginID;
datalist.PurchaseID = latest;
datalist.Stock_ID = item.Pid;
datalist.Stock_Name = item.ProductName;
datalist.Quantity = Convert.ToInt32(item.Qty);
datalist.Price = Convert.ToDecimal(item.Price);
datalist.Amount = Convert.ToDecimal(item.Amount);
datalist.Volume = Convert.ToInt32(item.Volume);
datalist.Total_Volume = Convert.ToInt32(k);
datalist.Weight = Convert.ToInt32(item.Weight);
datalist.Total_Weight = Convert.ToInt32(m);
datalist.Total_Percent = Convert.ToString(c);
datalist.Indirect_Cost_UnitPrice = Convert.ToString(f);
datalist.Landed_Cost_UnitPrice = Convert.ToString(h);
datalist.New_Amount = i;
data.Add(datalist);
}
var totalweight = data.Where(x => x.PurchaseID == latest).Select(x => x.Total_Weight).Sum();
var totalvolume = data.Where(x => x.PurchaseID == latest).Select(x => x.Total_Volume).Sum();
foreach (var item in tableListDto)
{
var z = Convert.ToInt32(item.Price);
var a = Convert.ToInt32(item.Qty); //Qty
var l = Convert.ToDecimal(item.Weight); //Weight
var j = Convert.ToDecimal(item.Volume); //Volume
var d = Math.Round(Convert.ToDecimal(((a * l) / totalweight) * 100), 2); //Total Percent Of Weight
var e = Convert.ToInt32(objModel.TotalOtherCost); //Total Other Cost
var f = Math.Round(Convert.ToDecimal(((d * e) / a) / 100), 2);
var h = Convert.ToDecimal(a + f); // Landed Cost Unit Price Of Weight
var i = Convert.ToString(h * a); // New Total Of Weight
var m = (a * j / totalvolume) * 100; //Total Percent Of Volume
var o = Math.Round(Convert.ToDecimal(((m * e) / a) / 100), 2); //Unit Price Of Volume
var q = Math.Round(Convert.ToDecimal(z + o), 2); // Landed Cost Unit Price Of Volume
var r = Convert.ToInt32(q * a); //New Total Of Volume
data.Where(x => x.PurchaseID == latest).FirstOrDefault();
data.Where(x => x.PurchaseID == latest).FirstOrDefault().Indirect_Cost_WeightUnitPrice = Convert.ToString(f);
data.Where(x => x.PurchaseID == latest).FirstOrDefault().Landed_Cost_WeightUnitPrice = Convert.ToString(h);
data.Where(x => x.PurchaseID == latest).FirstOrDefault().New_WeightAmount = Convert.ToDecimal(i);
data.Where(x => x.PurchaseID == latest).FirstOrDefault().Total_Percent_Volume = Convert.ToString(m);
data.Where(x => x.PurchaseID == latest).FirstOrDefault().Indirect_Cost_VolumeUnitPrice = Convert.ToString(o);
data.Where(x => x.PurchaseID == latest).FirstOrDefault().Landed_Cost_VolumeUnitPrice = Convert.ToString(q);
data.Where(x => x.PurchaseID == latest).FirstOrDefault().New_VolumeAmount = Convert.ToDecimal(r);
context.Entry(data).State = EntityState.Added;
context.SaveChanges();
}
foreach (var item in data)
{
order.LoginID = objModel.LoginID;
order.PurchaseID = item.PurchaseID;
order.Stock_ID = item.Stock_ID;
order.Quantity = item.Quantity;
order.Price = item.Price;
order.Amount = item.Amount;
order.CreatedBy = objModel.LoginID;
order.CreatedOn = objModel.CreatedOn;
order.UpdatedBy = objModel.LoginID;
order.UpdatedOn = objModel.UpdatedOn;
order.Status = StatusConstant.Active;
order.Stock_Name = item.Stock_Name;
order.Volume = item.Volume;
order.Total_Volume = item.Total_Volume;
order.Weight = item.Weight;
order.Total_Weight = item.Total_Weight;
context.OrderDetails.Add(order);
context.SaveChanges();
spread1.PurchaseID = item.PurchaseID;
spread1.OrderID = order.OrderID;
spread1.LoginID = item.LoginID;
spread1.Total_Percent = item.Total_Percent;
spread1.Indirect_Cost_UnitPrice = item.Indirect_Cost_UnitPrice;
spread1.Landed_Cost_UnitPrice = item.Landed_Cost_UnitPrice;
spread1.New_Amount = item.New_Amount;
spread1.Total_Percent_Volume = item.Total_Percent_Volume;
spread1.Indirect_Cost_VolumeUnitPrice = item.Indirect_Cost_VolumeUnitPrice;
spread1.Landed_Cost_VolumeUnitPrice = item.Landed_Cost_VolumeUnitPrice;
spread1.New_VolumeAmount = item.New_VolumeAmount;
spread1.Total_Percent_Weight = item.Total_Percent_Weight;
spread1.Indirect_Cost_WeightUnitPrice = item.Indirect_Cost_WeightUnitPrice;
spread1.Landed_Cost_WeightUnitPrice = item.Landed_Cost_WeightUnitPrice;
spread1.New_WeightAmount = item.New_WeightAmount;
context.PO_Landed_Cost_Spreads.Add(spread1);
context.SaveChanges();
}
}
else
{
order.LoginID = objModel.LoginID;
order.PurchaseID = latest;
order.CreatedBy = objModel.LoginID;
order.CreatedOn = objModel.CreatedOn;
order.UpdatedBy = objModel.LoginID;
order.UpdatedOn = objModel.UpdatedOn;
order.Status = StatusConstant.Active;
context.OrderDetails.Add(order);
context.SaveChanges();
PO_Landed_Cost_Spread spread = new PO_Landed_Cost_Spread();
spread.LoginID = objModel.LoginID;
spread.PurchaseID = latest;
spread.OrderID = order.OrderID;
context.PO_Landed_Cost_Spreads.Add(spread);
context.SaveChanges();
}
txn.Commit();
}
catch (Exception ex)
{
txn.Dispose();
success = false;
}
return success;
};
}
In this code i want to update records when first i need to find some values and then i need to update in the list view model and then i need to update in the table. But i am unable to do that. Please help me in this.

SQL to Linq-Entities

Please help me to convert this SQL query in LINQ-Enitites
select e.RowMeterialName,f.RowUnitName,*,isnull((b.Quantity - (Select SUM(a.Quantity) from PurchaseDetail a
join PurchaseMaster c on a.PurchaseId=c.PurchaseId
where a.RawMetId=b.RawMetrialId and c.PurchaseOrderId=b.PurchaseOrderId)),b.Quantity) as Remain
from PurchaseOrderDetail b
join RawMeterialMaster e on b.RawMetrialId=e.RawMetId
join RawUnitMaster f on e.RawUnitId=f.RowUnitId
where b.PurchaseOrderId=#PurchaseOrderId
Please help me.
This is a long shot, but you can try it:
PurchaseDetail
.Join
(
PurchaseMaster,
x=>x.PurchaseId,
x=>x.PurchaseId,
(detail,master)=>new {detail,master}
)
.Join
(
PurchaseOrderMaster,
x=>x.PurchaseOrderId,
x=>x.PurchaseOrderId,
(joined,ordermaster)=>new{detail=joined.detail,master=joined.master,ordermaster}
)
.Select
(
x=>
new{detail.Quantity,detail.RawMetId}
)
.GroupBy(x=>x.RawMetId)
.Select
(
x=>
new
{
RawMetId=x.Key,
Quantity=x.Sum(z=>z.Quantity)
}
)
.Join
(
PurchaseOrderDetail,
x=>x.RawMetrialId,
x=>x.RawMetId,
(subquery,orderdetail)=>new{subquery,Remain=subquery.Quantity - orderdetail.Quantity}
)
Thanks everybody but I found the result with this query
from b in db.PurchaseOrderDetails
select new
{
b.RawMeterialMaster.RowMeterialName,
PurOrderDetailId = b.PurOrderDetailId,
PurchaseOrderId = b.PurchaseOrderId,
RawMetrialId = b.RawMetrialId,
DueOn = b.DueOn,
Quantity = b.Quantity,
ItemRate = b.ItemRate,
MetrialUnitsId = b.MetrialUnitsId,
Remark = b.Remark,
RowUnitName = b.RawMeterialMaster.RawUnitMaster.RowUnitName,
ReOrderQuantity = (decimal?)b.RawMeterialMaster.ReOrderQuantity,
Remain = ((System.Decimal?)b.Quantity -
(from a in db.PurchaseDetails
where
a.RawMetId == b.RawMetrialId &&
a.PurchaseMaster.PurchaseOrderId == b.PurchaseOrderId
select new
{
a.Quantity
}).Sum(p => p.Quantity) ?? (System.Decimal?)b.Quantity)
};

ExecuteSqlCommand with output parameter

I'm using Entity Framework in an ASP.NET MVC3 application and I'm trying to use the following code:
var token = "";
this.Database.ExecuteSqlCommand("exec dbo.MyUsp", new SqlParameter("token", token));
My stored proc signature is:
CREATE PROCEDURE MyUSP(#token varchar(10) OUT)
(...)
When I use this code I get an error saying that parameter "#token" was expected but not supplied.
How do I tell EF that the token parameter is for output?
I ended up using this to get it working, but I'm sure there's a more optimal way:
var p = new SqlParameter
{
ParameterName = "token",
DbType = System.Data.DbType.String,
Size = 100,
Direction = System.Data.ParameterDirection.Output
};
var resp = this.Database.SqlQuery<String>("exec dbo.usp_GetRequestToken #token", p);
return resp.First();
var outParam = new SqlParameter();
outParam.ParameterName = "OutPutParametname";
outParam.SqlDbType = SqlDbType.Bit;//DataType Of OutPut Parameter
outParam.Direction = ParameterDirection.Output;
db.Database.ExecuteSqlCommand("EXEC ProcedureName #Param1,#Param2 OUTPUT", new SqlParameter("Param1", value), outParam);
object outParamValue = Convert.ToBoolean(outParam.Value);
You need to indicate the direction in the parameter. For example, try something like this:
var p = new SqlParameter("token", token);
p.Direction = ParameterDirection.InputOutput;
this.Database.ExecuteSqlCommand("exec dbo.MyUsp", p);
I solved this issue with following SQL and Entity Framework code
SP :
ALTER PROCEDURE [dbo].[SaveSingleColumnValueFromGrid]
(
#TableName VARCHAR(200),
#ColumnName VARCHAR (200),
#CompareField VARCHAR(200),
#CompareValue VARCHAR(200),
#NewValue VARCHAR(200),
#Result INT OUTPUT
)
AS
BEGIN
DECLARE #SqlString NVARCHAR(2000),
#id INTEGER = 0;
IF #CompareValue = ''
BEGIN
SET #SqlString = 'INSERT INTO ' + #TableName + ' ( ' + #ColumnName + ' ) VALUES ( ''' + #NewValue + ''' ) ; SELECT #id = SCOPE_IDENTITY()';
EXECUTE sp_executesql #SqlString, N'#id INTEGER OUTPUT', #id OUTPUT
END
ELSE
BEGIN
SET #SqlString = 'UPDATE ' + #TableName + ' SET ' + #ColumnName + ' = ''' + #NewValue + ''' WHERE ' + #CompareField + ' = ''' + #CompareValue + '''';
EXECUTE sp_executesql #SqlString
set #id = ##ROWCOUNT
END
SELECT #Result = #id
END
Entity Framework Code :
public FieldUpdateResult SaveSingleColumnValueFromGrid(string tableName, string tableSetFieldName, string updatedValue, string tableCompareFieldName, string uniqueFieldValue)
{
var fieldUpdateResult = new FieldUpdateResult() ;
var isNewRecord = false;
if (string.IsNullOrWhiteSpace(uniqueFieldValue))
{
uniqueFieldValue = string.Empty;
isNewRecord = true;
}
using (var dbContext = new DBEntities())
{
var resultParameter = new SqlParameter("#Result", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
var recordsAffected = dbContext.Database.ExecuteSqlCommand("SaveSingleColumnValueFromGrid #TableName,#ColumnName,#CompareField,#CompareValue,#NewValue,#Result out",
new SqlParameter("#TableName", tableName),
new SqlParameter("#ColumnName", tableSetFieldName),
new SqlParameter("#CompareField", tableCompareFieldName),
new SqlParameter("#CompareValue", uniqueFieldValue),
new SqlParameter("#NewValue", updatedValue),
resultParameter);
fieldUpdateResult.Success = recordsAffected > 0;
if (isNewRecord)
{
fieldUpdateResult.NewId = (int)resultParameter.Value;
}
else
{
fieldUpdateResult.AffectedRows = (int)resultParameter.Value;
}
}
return fieldUpdateResult;
}
var db = new DBContext();
var outParam = new SqlParameter
{
ParameterName = "#Param",
DbType = System.Data.DbType.String,
Size = 20,
Direction = System.Data.ParameterDirection.Output
};
var r = db.Database.ExecuteSqlCommand("EXEC MyStoredProd #Param OUT",outParam );
Console.WriteLine(outParam.Value);
The main part i see everyone is missing, is the OUT keyword needed after #Param.
Below is what I do for Oracle using the DevArt driver. I have a package.proc called P_SID.SID_PGet that returns a single string value. The proc is:
PROCEDURE SID_PGet(io_SID OUT varchar2) is
Begin
io_SID:=GetSID; -- GetSID just goes off and gets the actual value
End;
Below is how I call it and retrieve the SID value (I'm using this with EF 4.1 code first and this method is in the DbContext):
/// <summary>
/// Get the next SID value from the database
/// </summary>
/// <returns>String in X12345 format</returns>
public string GetNextSId()
{
var parameter = new Devart.Data.Oracle.OracleParameter("io_SID", Devart.Data.Oracle.OracleDbType.VarChar, ParameterDirection.Output);
this.Database.ExecuteSqlCommand("BEGIN P_SID.SID_PGet(:io_SID); END;", parameter);
var sid = parameter.Value as string;
return sid;
}

Resources