How to run sql query with bit field when using FromSql - entity-framework

I have this query:
return await this.DbContext.SearchRequestInfos.FromSql(
$#"{SqlStrings.SP.SearchSearchRequests}
#searchRequestId = {input.SearchRequestId},
#customerId = {input.CustomerId},
#customerName = {input.CustomerName},
#code = {input.Code},
#description = {input.Description},
#isGeneric = {input.IsGeneric},
#isActive = {input.IsActive}
"
).AsNoTracking().ToListAsync();
which creates this sql:
Executed DbCommand (69ms) [Parameters=[#p0='?' (Size = 4000), #p1='?', #p2='?', #p3='?', #p4='?', #p5='?', #p6='?' (DbType = Boolean), #p7='?' (DbType = Boolean)], CommandType='Text', CommandTimeout='30']
Portal> #p0
Portal> #searchRequestId = #p1,
Portal> #customerId = #p2,
Portal> #customerName = #p3,
Portal> #code = #p4,
Portal> #description = #p5,
Portal> #isGeneric = #p6,
Portal> #isActive = #p7
The issue is that #isGeneric and #isActive are bit fields, but the value is not getting used. In other words, the value should be true, which should be translated to 1, but it is not.
Is this a bug in EF Core, or am I doing something wrong?
The workaround is to add a property to convert the value to an int, and then the SQL works as expected.
public int? IsGenericBit { get {
if(this.IsGeneric.HasValue) return this.IsGeneric.Value ? 1 : 0;
return null;
} }
public int? IsActiveBit { get {
if (this.IsActive.HasValue) return this.IsActive.Value ? 1 : 0;
return null;
} }
Portal> Executed DbCommand (63ms) [Parameters=[#p0='?' (Size = 4000), #p1='?', #p2='?', #p3='?', #p4='?', #p5='?', #p6='?' (DbType = Int32), #p7='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
Portal> #p0
Portal> #searchRequestId = #p1,
Portal> #customerId = #p2,
Portal> #customerName = #p3,
Portal> #code = #p4,
Portal> #description = #p5,
Portal> #isGeneric = #p6,
Portal> #isActive = #p7
Note that that it specificies #6 and #7 as Int32 although they are actual bit in the database.
So the question is: Am I doing something wrong or is this a bug?

Related

Salesforce Trigger Test Class

below is my Apex Trigger. I am a beginner and trying to write its test class but continuously getting error "System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Error: You can't select products until you've chosen a price book for this opportunity on the products related list.: []".
trigger TrgrOptyHighestCustmorePrice on Opportunity (before insert, before update)
{
public Id oid;
public String bidType;
public String BUCode;
for(Opportunity o : trigger.new)
{
oid = o.Id;
bidType = o.BidType__c;
BUCode = o.Business_Line_BU__c;
}
List<OpportunityLineItem> oliList = new list<OpportunityLineItem>([SELECT id, Customer_Price__c, ReCat_Product_Line__c
FROM OpportunityLineItem
WHERE OpportunityId =: oid ORDER BY
Customer_Price__c DESC LIMIT 1]);
for(OpportunityLineItem oli : oliList)
{
if(bidType == 'Competitive' && oli.ReCat_Product_Line__c == 'DMS')
{
BUCode = 'BL.619';
}
if(bidType == 'Competitive' && (oli.ReCat_Product_Line__c == 'EMS' || oli.ReCat_Product_Line__c == 'GMS'))
{
BUCode = 'BL.620';
}
if(bidType == 'Competitive' && oli.ReCat_Product_Line__c == 'MMS')
{
BUCode = 'BL.622';
}
if(bidType == 'Sole Sourced' && oli.ReCat_Product_Line__c == 'DMS')
{
BUCode = 'BL.624';
}
if(bidType == 'Sole Sourced' && (oli.ReCat_Product_Line__c == 'EMS' || oli.ReCat_Product_Line__c == 'GMS'))
{
BUCode = 'BL.621';
}
if(bidType == 'Sole Sourced' && oli.ReCat_Product_Line__c == 'MMS')
{
BUCode = 'BL.623';
}
}
for(Opportunity opt : trigger.new)
{
opt.Business_Line_BU__c = BUCode;
}
}
Test Class
#isTest(seeAllData=true)
public class Test_TrgrOptyHighestCustmorePrice {
private static testmethod void TrgrOptyHighestCustmorePriceTest(){
Test.startTest();
//Insert a test product.
Product2 p1 = new Product2(Name='Product Monthly 1111', isActive=true, CurrencyIsoCode='USD', ReCat_Product_Line__c = 'DMS');
insert p1;
// Get standard price book ID.
Id pricebookId = Test.getStandardPricebookId();
// Insert a price book entry for the standard price book.
PricebookEntry standardPrice = new PricebookEntry(
Pricebook2Id = pricebookId, Product2Id = p1.Id,
UnitPrice = 10000, IsActive = true);
insert standardPrice;
Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
insert customPB;
PricebookEntry customPrice = new PricebookEntry(
Pricebook2Id = customPB.Id, Product2Id = p1.Id,
UnitPrice = 12000, IsActive = true);
insert customPrice;
// Insert Opportunity
Opportunity opt = new Opportunity(Name='Test',StageName='Prospect',
CloseDate=date.today(),BidType__c = 'Competitive',
Business_Line_BU__c = 'BL.619',
PriceBook2 = customPB);
insert opt;
OpportunityLineItem optLI = new OpportunityLineItem(OpportunityId = opt.id, Product2Id = p1.Id);
insert optLI;
update opt;
Test.stopTest();
}
}
I am unable to understand how can I test my simple trigger.
Its because u do not fill all required fields for the Opportunity Line Item. See: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_opportunitylineitem.htm for required fields.
This as an example will work:
OpportunityLineItem optLI = new OpportunityLineItem(OpportunityId = opt.id, Product2Id = p1.Id, TotalPrice = 100, PricebookEntryId=customPrice.Id, Quantity =3);
First Insert the opportunity.
Then update the opportunity with the pricebookid.
// Insert Opportunity
Opportunity opt = new Opportunity(Name='Test',StageName='Prospect',
CloseDate=date.today(),BidType__c = 'Competitive',
Business_Line_BU__c = 'BL.619'
);
insert opt;
opt.PriceBook2 = customPB;
update opt;

Web API 2 method developed using ADO.NET is not performing well, takes 53 seconds

I am creating API for Android app using Asp.Net Web API2. There is a method which fetches members data from the table. I am sorting and listing members based on arrangements(int) and name(string). The first sort by arrangements which value is not 0. then sort by name which value is 0. Everything working perfect but query execution taking 53234 ms as shown in postman.PErformance goes worst when I use EF6. I tested it using live URL and not on localhost. I have cloud server. Please check and help me in performance improvement. There are around 1000 rows/records only. There is an another query/stored procedure also which list nearby members based on latitude and longitude and execution time is hardly 2 seconds. Let me know if you need more information. Thanks
API Method
[HttpGet]
[ActionName("GetAllMembersOfClub")]
public APIResult GetAllMembersOfClub()
{
APIResult apiResult = new APIResult();
List<MemberData> lstMember = new List<MemberData>();
var cmd = new SqlCommand("Rotary1.usp_GetMembersWithArrangements", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#clubId", DbType.Int32).Value = clubID;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
var objMember = new MemberData();
objMember.CountryCode = dr["CountryCode"].ToString();
objMember.ClubName = dr["ClubName"].ToString();
objMember.Name = dr["name"].ToString();
objMember.Classification = dr["Classification"].ToString();
objMember.OfficeAdrs1 = dr["OfficeAdrs1"].ToString();
objMember.OfficeAdrs2 = dr["OfficeAdrs2"].ToString();
objMember.OfficeAdrs3 = dr["OfficeAdrs3"].ToString();
objMember.ResAdrs1 = dr["ResAdrs1"].ToString();
objMember.ResAdrs2 = dr["ResAdrs2"].ToString();
objMember.ResAdrs3 = dr["ResAdrs3"].ToString();
objMember.Spouse = dr["Wife"].ToString();
objMember.Phone = dr["Phone"].ToString();
objMember.Mobile = "+" + dr["CountryCode"].ToString() + dr["Mobile"].ToString();
objMember.EmailId = dr["EmailId"].ToString();
objMember.Since = dr["Since"].ToString();
objMember.Title1 = dr["title1"].ToString();
objMember.Title2 = dr["title2"].ToString();
objMember.Title3 = dr["title3"].ToString();
objMember.Title4 = dr["title4"].ToString();
objMember.PostHeld = dr["PostHeld"].ToString();
objMember.Imgg = dr["imgg"].ToString();
objMember.Anniversary = dr["Aniversary"].ToString();
objMember.Position = dr["Position"].ToString();
objMember.Ophone = dr["ophone"].ToString();
objMember.Children = dr["Children"].ToString();
objMember.Spouse = dr["Wife"].ToString();
objMember.Latitude = dr["Latitude"].ToString();
objMember.Longitude = dr["Longitude"].ToString();
objMember.Mobile10 = dr["mobile10"].ToString();
objMember.Mobile2 = dr["mobile2"].ToString();
objMember.Mobile3 = dr["mobile3"].ToString();
objMember.Mobile4 = dr["mobile4"].ToString();
objMember.Mobile5 = dr["mobile5"].ToString();
objMember.Mobile6 = dr["mobile6"].ToString();
objMember.Mobile7 = dr["mobile7"].ToString();
objMember.Mobile8 = dr["mobile8"].ToString();
objMember.Mobile9 = dr["mobile9"].ToString();
objMember.Noti = dr["noti"].ToString();
objMember.Arrange = dr["arrange"].ToString();
try
{
objMember.DOB = Convert.ToDateTime(dr["DOB"].ToString()).ToString("dd-MM-yyy");
}
catch (Exception)
{
objMember.DOB = "";
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile2) || objMember.Mobile2 != "")
{
objMember.Mobile2 = "+" + dr["CountryCode"].ToString() + dr["mobile2"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile3) || objMember.Mobile3 != "")
{
objMember.Mobile3 = "+" + dr["CountryCode"].ToString() + dr["mobile3"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile4) || objMember.Mobile4 != "")
{
objMember.Mobile4 = "+" + dr["CountryCode"].ToString() + dr["mobile4"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile5) || objMember.Mobile5 != "")
{
objMember.Mobile5 = "+" + dr["CountryCode"].ToString() + dr["mobile5"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile6) || objMember.Mobile6 != "")
{
objMember.Mobile6 = "+" + dr["CountryCode"].ToString() + dr["mobile6"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile7) || objMember.Mobile7 != "")
{
objMember.Mobile7 = "+" + dr["CountryCode"].ToString() + dr["mobile7"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile8) || objMember.Mobile8 != "")
{
objMember.Mobile8 = "+" + dr["CountryCode"].ToString() + dr["mobile8"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile9) || objMember.Mobile9 != "")
{
objMember.Mobile9 = "+" + dr["CountryCode"].ToString() + dr["mobile9"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile10) || objMember.Mobile10 != "")
{
objMember.Mobile10 = "+" + dr["CountryCode"].ToString() + dr["mobile10"].ToString();
}
lstMember.Add(objMember);
}
dr.Close();
conn.Close();
cmd = new SqlCommand("Rotary1.usp_GetMembersWithArrangements1", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#clubId", DbType.Int32).Value = clubID;
conn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
var objMember = new MemberData();
objMember.CountryCode = dr["CountryCode"].ToString();
objMember.ClubName = dr["ClubName"].ToString();
objMember.Name = dr["name"].ToString();
objMember.Classification = dr["Classification"].ToString();
objMember.OfficeAdrs1 = dr["OfficeAdrs1"].ToString();
objMember.OfficeAdrs2 = dr["OfficeAdrs2"].ToString();
objMember.OfficeAdrs3 = dr["OfficeAdrs3"].ToString();
objMember.ResAdrs1 = dr["ResAdrs1"].ToString();
objMember.ResAdrs2 = dr["ResAdrs2"].ToString();
objMember.ResAdrs3 = dr["ResAdrs3"].ToString();
objMember.Spouse = dr["Wife"].ToString();
objMember.Phone = dr["Phone"].ToString();
objMember.Mobile = "+" + dr["CountryCode"].ToString() + dr["Mobile"].ToString();
objMember.EmailId = dr["EmailId"].ToString();
objMember.Since = dr["Since"].ToString();
objMember.Title1 = dr["title1"].ToString();
objMember.Title2 = dr["title2"].ToString();
objMember.Title3 = dr["title3"].ToString();
objMember.Title4 = dr["title4"].ToString();
objMember.PostHeld = dr["PostHeld"].ToString();
objMember.Imgg = dr["imgg"].ToString();
objMember.Anniversary = dr["Aniversary"].ToString();
objMember.Position = dr["Position"].ToString();
objMember.Ophone = dr["ophone"].ToString();
objMember.Children = dr["Children"].ToString();
objMember.Spouse = dr["Wife"].ToString();
objMember.Latitude = dr["Latitude"].ToString();
objMember.Longitude = dr["Longitude"].ToString();
objMember.Mobile10 = dr["mobile10"].ToString();
objMember.Mobile2 = dr["mobile2"].ToString();
objMember.Mobile3 = dr["mobile3"].ToString();
objMember.Mobile4 = dr["mobile4"].ToString();
objMember.Mobile5 = dr["mobile5"].ToString();
objMember.Mobile6 = dr["mobile6"].ToString();
objMember.Mobile7 = dr["mobile7"].ToString();
objMember.Mobile8 = dr["mobile8"].ToString();
objMember.Mobile9 = dr["mobile9"].ToString();
objMember.Noti = dr["noti"].ToString();
objMember.Arrange = dr["arrange"].ToString();
try
{
objMember.DOB = Convert.ToDateTime(dr["DOB"].ToString()).ToString("dd-MM-yyy");
}
catch (Exception)
{
objMember.DOB = "";
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile2) || objMember.Mobile2 != "")
{
objMember.Mobile2 = "+" + dr["CountryCode"].ToString() + dr["mobile2"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile3) || objMember.Mobile3 != "")
{
objMember.Mobile3 = "+" + dr["CountryCode"].ToString() + dr["mobile3"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile4) || objMember.Mobile4 != "")
{
objMember.Mobile4 = "+" + dr["CountryCode"].ToString() + dr["mobile4"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile5) || objMember.Mobile5 != "")
{
objMember.Mobile5 = "+" + dr["CountryCode"].ToString() + dr["mobile5"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile6) || objMember.Mobile6 != "")
{
objMember.Mobile6 = "+" + dr["CountryCode"].ToString() + dr["mobile6"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile7) || objMember.Mobile7 != "")
{
objMember.Mobile7 = "+" + dr["CountryCode"].ToString() + dr["mobile7"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile8) || objMember.Mobile8 != "")
{
objMember.Mobile8 = "+" + dr["CountryCode"].ToString() + dr["mobile8"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile9) || objMember.Mobile9 != "")
{
objMember.Mobile9 = "+" + dr["CountryCode"].ToString() + dr["mobile9"].ToString();
}
if (!string.IsNullOrWhiteSpace(objMember.Mobile10) || objMember.Mobile10 != "")
{
objMember.Mobile10 = "+" + dr["CountryCode"].ToString() + dr["mobile10"].ToString();
}
lstMember.Add(objMember);
}
dr.Close();
conn.Close();
apiResult.ReturnData = lstMember;
apiResult.ReturnCode = "1";
apiResult.ReturnMessage = "success";
return apiResult;
}
Queries/Stored Procedures
USE [myDb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [Rotary1].[usp_GetMembersWithArrangements]
#clubId INT
As
BEGIN
BEGIN
select * from main where arrange<>0 and club=#clubId order by arrange desc
END
END
GO
Second Procedure
USE [myDb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [Rotary1].[usp_GetMembersWithArrangements1]
#clubId INT
As
BEGIN
BEGIN
select * from main where arrange=0 and club=#clubId order by name
END
END
GO
Below is table schema
CREATE TABLE [dbo].[main](
[ID] [int] IDENTITY(1,1) NOT NULL,
[title1] [varchar](max) NULL,
[title2] [varchar](max) NULL,
[title3] [varchar](max) NULL,
[title4] [varchar](max) NULL,
[Name] [varchar](max) NULL,
[Classification] [varchar](max) NULL,
[position] [varchar](max) NULL,
[PostHeld] [varchar](max) NULL,
[OfficeAdrs1] [text] NULL,
[OfficeAdrs2] [text] NULL,
[OfficeAdrs3] [text] NULL,
[ophone] [varchar](max) NULL,
[Phone] [varchar](max) NULL,
[Mobile] [varchar](max) NULL,
[EmailId] [varchar](max) NULL,
[ResAdrs1] [text] NULL,
[ResAdrs2] [text] NULL,
[ResAdrs3] [text] NULL,
[Wife] [varchar](max) NULL,
[children] [varchar](max) NULL,
[DOB] [date] NULL,
[Since] [varchar](max) NULL,
[imgg] [text] NULL,
[Aniversary] [varchar](max) NULL,
[arrange] [int] NULL,
[club] [int] NULL,
[noti] [int] NULL,
[ClubName] [varchar](200) NULL,
[Latitude] [varchar](200) NULL,
[Longitude] [varchar](200) NULL,
[mobile2] [varchar](20) NULL,
[mobile3] [varchar](20) NULL,
[mobile4] [varchar](20) NULL,
[mobile5] [varchar](20) NULL,
[mobile6] [varchar](20) NULL,
[mobile7] [varchar](20) NULL,
[mobile8] [varchar](20) NULL,
[mobile9] [varchar](20) NULL,
[mobile10] [varchar](20) NULL,
[CountryCode] [varchar](10) NULL,
[Status] [int] NULL CONSTRAINT [DF_main_Status] DEFAULT ((1)),
CONSTRAINT [PK_main] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
public List<Member> GetMembers(string name="")
{
var param1 = new SqlParameter("#Name",name );
var result = _Context.Database.SqlQuery<Member>("exec GetMembersList #Name", param1).ToList();
return result;
}

Pivot Runner: force delete of existing constraint that match a constraint needed for the new model

Facing same issue, is there any progress on this one :
http://www.softfluent.com/product/codefluent-entities/knowledge-center/point-sql-server-producer-to-production-db-instead-of-using-pivot-producer
Thanks for your answer,
EDIT: this is the code used to delete all the constraints
private static void RemoveCodeFluentConstraintsTable(IList<PivotRunnerConstraint> constraints, String connectionString)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT tables.name as tableName, default_constraints.name as constraintName FROM sys.all_columns INNER JOIN sys.tables ON all_columns.object_id = tables.object_id INNER JOIN sys.schemas ON tables.schema_id = schemas.schema_id INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id", con))
{
foreach (PivotRunnerConstraint constraint in constraints)
{
String tableName = constraint.ParentName;
String constraintName = constraint.Name;
if (tableName != null && constraintName != null)
{
SqlCommand cmdConstraint = new SqlCommand("ALTER TABLE [MySchema].[" + tableName + "] DROP CONSTRAINT [" + constraintName + "]", con);
cmdConstraint.ExecuteNonQuery();
}
}
//con.Close();
}
}
return;
}
I went for using a custom naming convention using table name prefixing the generated constraint name.
public class MyNamingConvention : FormatNamingConvention
{
public override string GetName(INamedObject obj, IDictionary context)
{
Column column = obj as Column;
if (column != null && column.Table != null)
{
var name = context["name"] as string;
if (name != null && (name.StartsWith("DF_")))
{
return column.Table.Name + base.GetName(obj, context);
}
}
return base.GetName(obj, context);
}
}
At the same time, I also had to delete existing constraints to avoid collision:
private static void RemoveCodeFluentConstraints(string connectionString)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT c.name, t.name FROM sys.objects c, sys.objects t, sys.schemas s WHERE c.type IN('F', 'PK', 'FK', 'UQ', 'D') AND c.parent_object_id = t.object_id and t.SCHEMA_ID = s.schema_id AND t.type = 'U' AND s.name = 'MySchema' ORDER BY c.type", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
using (SqlConnection con1 = new SqlConnection(connectionString))
{
con1.Open();
while (dr.Read())
{
String constraintName = dr[0].ToString();
String tableName = dr[1].ToString();
if (tableName != null && constraintName != null)
{
String cmdConstraintSql = "ALTER TABLE [MySchema].[" + tableName + "] DROP CONSTRAINT [" + constraintName + "]";
ActivityLog.Write("Execute " + cmdConstraintSql, ActivityLogsFile);
SqlCommand cmdConstraint = new SqlCommand(cmdConstraintSql, con1);
cmdConstraint.ExecuteNonQuery();
}
}
con1.Close();
}
}
}
con.Close();
}
return;
}
Other problem were related to definition of pivot file not being picked correctly: Pivot Runner null command

Postgresql update - Using ArrayList

I am getting an exception on update of postgres:
org.postgresql.util.PSQLException: Can't infer the SQL type...
Here is the code where in I build the sql statement dynamically and append the params:
public Boolean update(UserData usrData){
String sqlUpdateUser = "UPDATE \"USER\" ";
String sqlSetValues = "SET";
String sqlCondition = "Where \"USER_ID\" = ? ";
List<Object> params = new ArrayList<Object>();
List<Integer> types = new ArrayList<Integer>();
if(usrData.getFirstName() != null){
sqlSetValues = sqlSetValues.concat(" \"FIRST_NAME\" = ? ").concat(", ");
params.add(usrData.getFirstName());
types.add(Types.VARCHAR);
}
if(usrData.getMiddleName() != null){
sqlSetValues = sqlSetValues.concat("\"MIDDLE_NAME\" = ? ");
params.add(usrData.getMiddleName());
types.add(Types.VARCHAR);
}
params.add(usrData.getUserId());
types.add(Types.BIGINT);
Object[] updateParams = new Object[params.size()];
updateParams = params.toArray(updateParams);
Integer[] paramTypes = new Integer[types.size()];
paramTypes = types.toArray(paramTypes);
sqlUpdateUser = sqlUpdateUser.concat(sqlSetValues).concat(sqlCondition);
int rowsAffected = this.jdbcTemplate.update(sqlUpdateUser, updateParams, paramTypes);
if(rowsAffected > 0){
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}
And table schema for the USER table is:
"FIRST_NAME" character varying(50),
"MIDDLE_NAME" character varying(50),
If I do an update statically without using the collection, but by using Array, I see no issue.
Code snipped using arrays:
Object[] param = { usrData.getFirstName(), usrData.getMiddleName(), usrData.getUserId() };
int[] type = { Types.VARCHAR, Types.VARCHAR, Types.BIGINT };
int rowsAffected = this.jdbcTemplate.update(sqlUpdateUser, param, type);
Am I missing something?
Thanks
K
Move these lines
Object[] updateParams = new Object[params.size()];
updateParams = params.toArray(updateParams);
Integer[] paramTypes = new Integer[types.size()];
paramTypes = types.toArray(paramTypes);
beneath
params.add(usrData.getUserId());
types.add(Types.INTEGER);
In your case you are missing to add usrData.getUserId() in updateParams.

consume int result returned from stored procedure in MVC4

I have created stored procedure like this:
ALTER procedure [dbo].[takeOrder]
(
#id int = 0,
#userid int = 0,
#diningid int,
#amount float
)
as
begin
declare #countt as int
select #countt = COUNT(*)
from Order_master
where dining_Id = #diningid and isActive = 1
if #countt <> 0
begin
update Order_master
set amount = #amount
where dining_Id = #diningid and isActive = 1;
end
else
begin
insert into Order_master(userid, dining_Id, amount, [date], isActive)
values (#userid, #diningid, #amount, GETDATE(), 1)
end
--select amount from Order_master where dining_Id=#diningid and isActive=1
select oid
from Order_master
where dining_Id = #diningid and isActive = 1
end
In controller I am trying to get return result as mention below:
[HttpPost]
public ActionResult takeOrder(Order_master order,List<Menu_info> menu)
{
String msg = "";
int oid;
if (ModelState.IsValid)
{
try
{
Order_master objOreder = new Order_master
{
amount = order.amount,
isActive = 1,
date = order.date,
dining_Id = order.dining_Id,
userId = order.userId
};
object orderId = db.takeOrder(objOreder.oid, objOreder.userId, objOreder.dining_Id, objOreder.amount);
oid = (int)orderId;
msg = "success..!!";
}
catch (Exception ex)
{
msg = "error...";
}
}
else
{
msg = "please provide info";
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
else
{
return View();
}
}
But it returns an exception
Cannot convert type 'System.Data.Objects.ObjectResult' to 'int'
I am not able to get single return value from stored procedure.
Hope I get the right solution.
object orderId = db.takeOrder(objOreder.oid, objOreder.userId, objOreder.dining_Id, objOreder.amount);
oid = (int)orderId;
Try this conversion method.
oid = Convert.ToInt32(orderId);
You can use like
public int InsertWebProperty(int orgid, int? userid, string address, string property_Id, string latitude, string longitude, int? compamyid)
{
return Convert.ToInt32((db.InsertWebProperty(orgid, userid, address, property_Id, latitude, longitude, 0)).FirstOrDefault().recidentity.Value);
}
Please let me know if it not worked for you..
Thanks
db.TakeOrder().FirstOrDefault().ToString() = One value returned as a string
db.TakeOrder().FirstOrDefault().ToList() = Row returned as a list.
Create view as
CREATE VIEW [dbo].[vScalar]
AS
SELECT '' AS Value
In Stored Procedure return
SELECT CAST(orderId AS VARCHAR(10)) AS value
In Entity Framework, set function return use entity vScalar
In code
vScalar orderId = db.takeOrder(objOreder.oid, objOreder.userId, objOreder.dining_Id, objOreder.amount).FirstOrDefault;
oid = (int)orderId.value;