Related
This question already has an answer here:
Column <column name> does not belong to table
(1 answer)
Closed 4 years ago.
The thing is in my view employee page I have a option called edit where it goes to new page to edit the details of employee here.I am using this line to get the data from sql server to text box and it's showing this error, I have cross checked the column name hell lot of times I don't know where the error is. I have been using a stored procedure to get value from the database
I have all the process for this none helped me.
txtrcountry.Text = dtst.Tables[0].Rows[0]["RCountry"].ToString();
This is my stored procedure which is used to insert edited data to database
USE [PMS v1.0]
GO
/****** Object: StoredProcedure [dbo].[editemp] Script Date: 15-02-2019 09:54:19 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[editemp](#empid int )
as
begin
select Employeeid,firstname,lastname,Gender,convert(varchar(20),(convert(date,DateofBirthday,105))) as DateofBirthday,Mobilenumber,
Alternatenumber,Emailid,AlternateEmail,Fathername,
Mothername,AadhaarCardNo,PanCardNo,PassportNo,UserName,Password,RAddressLine1,RAddressLine2,RCity,RState,RZipCode,RCountry,
PAddressLine1,PAddressLine2,PCity,PState,PZipCode,PCountry,OAddressLine1,
OAddressLine2,OCity,OState,OZipCode,OCountry from newemployee with(nolock) where Employeeid=#empid
select sno,Employeeid,languagename,Expertise from employeelanguges with(nolock) where Employeeid=#empid
end
This is another stored procedure which is used to get the data from database
USE [PMS v1.0]
GO
/****** Object: StoredProcedure [dbo].[anotherpageupdateemp] ScriptDate: 15-02-2019 09:57:36 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[anotherpageupdateemp]
(
#Employeeid int,#firstname nvarchar(20),#lastname nvarchar(40),#Gender nvarchar(10),#DateOfBirth nvarchar(20),
#Fathername nvarchar(20),#Mothername nvarchar(20),
#Emailid nvarchar(20),#AlternateEmail nvarchar(20),#AadhaarCardNo nvarchar(20),
#PanCardNo nvarchar(20),#PassportNo nvarchar(20),#UserName nvarchar(20),
#Password nvarchar(20),#Mobilenumber nvarchar(20),#Alternatenumber nvarchar(20),#RAddressLine1 nvarchar(40),
#RAddressLine2 nvarchar(40),#RCity nvarchar(30),#RState nvarchar(30),#RZipCode nvarchar(20),#RCountry nvarchar(30),
#PAddressLine1 nvarchar(30),#PAddressLine2 nvarchar(30),
#PCity nvarchar(20),#PState nvarchar(20),#PZipCode nvarchar(20),#PCountry nvarchar(30),#OAddressLine1 nvarchar(30),#OAddressLine2 nvarchar(30),#OCity nvarchar(20),
#OState nvarchar(20),#OZipCode nvarchar(20),#OCountry nvarchar(30)
)
as
begin
update newemployee set firstname=#firstname,lastname=#lastname,Gender=#Gender,DateofBirthday=#DateOfBirth,Fathername=#Fathername,Mothername=#Mothername,
Emailid=#Emailid,AlternateEmail=#AlternateEmail,AadhaarCardNo=#AadhaarCardNo,PanCardNo=#PanCardNo,PassportNo=#PassportNo,UserName=#UserName,
Password=#Password,Mobilenumber=#Mobilenumber,Alternatenumber=#Alternatenumber,RAddressLine1=#RAddressLine1,
RAddressLine2=#RAddressLine2,RCity=#RCity,RState=#RState,RZipCode=#RZipCode,RCountry=#RCountry,PAddressLine1=#PAddressLine1,PAddressLine2=#PAddressLine2,
PCity=#PCity,PState=#PState,PZipCode=#PZipCode,PCountry=#PCountry,OAddressLine1=#OAddressLine1,OAddressLine2=#OAddressLine2,OCity=#OCity,OState=#OState,OZipCode=#OZipCode,OCountry=#OCountry
where Employeeid=#Employeeid
end
txtrcountry is the textbox id and RCountry is the column name I should get the details of the country in the textbox.
Your number of parameters in C# side isn't same as the stored procedure. Your parameters should correspond like this:
#Employeeid
#firstname
#lastname
#Gender
#DateOfBirth
#Fathername
#Mothername
#Emailid
#AlternateEmail
#AadhaarCardNo
#PanCardNo
#PassportNo
#UserName
#Password
#Mobilenumber
#Alternatenumber
#RAddressLine1
#RAddressLine2
#RCity
#RState
#RZipCode
#RCountry
#PAddressLine1
#PAddressLine2
#PCity
#PState
#PZipCode
#PCountry
#OAddressLine1
#OAddressLine2
#OCity
#OState
#OZipCode
#OCountry
yes I have solved the whole error Thanks #GaganDeep and #Gauravsa for helping me this error is solved
I have passed an extra argument in C# code
cmd.Parameters.AddWithValue("#Role", empenty.Role);
I removed this line which solved my Bug
I working on an MVC product using Database first entity framework approach, I added a few stored procedure to the EDM, but some are returning string instead of the model type. I have deleted the model.edmx, removed the connection string from the web.config file and re- added model1.edmx file to the project, yet, some still have string as return type, I have also created a viewmodel class and use it in place of the string, yet no luck. I want to be able to add procedure to return type of the model.
Stored Procedure in Model1.Context class:
public virtual ObjectResult<string> PreLoadWorkflowType()
{
return((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<string>("PreLoadWorkflowType");
}
I want the generated stored procedure to look like this instead:
public virtual ObjectResult<PreLoadWorkflowType> PreLoadWorkflowType()
{ return((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<PreLoadWorkflowType>("PreLoadWorkflowType");
}
I have been adding stored procedure to the EDM file all the while, i have not experience this before, I will appreciate assistance from anyone who had experienced and resolved this.
Stored Procedure:
USE [databsename]
GO
/****** Object: StoredProcedure [dbo].[PreLoadWorkflowType] Script Date:
1/30/2018 11:46:15 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[PreLoadWorkflowType]
-- Add the parameters for the stored procedure here
--#RequestType varchar(10),
--#WorkFlowType varchar(20)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
select distinct workflow_type AS WorkflowType from V_ui_View where
workflow_type is not null
END
Where V_ui_View is a view
F-ES Sitecore a senior Developer in another platform posted an answer to this, and it resolved the issue. Check the solution below:
In the model browser select your SP and in the properties window click "Return Type" then click the ellipses button to open the "Edit Function Import" dialog.
In the "Returns a collection of" if you want the SP to return instances of an existing entity then select Entities and the relevant one. If the data doesn't match an existing entity then select "Complex", click "Get Column Information", then click "Create New Complex Type" and it'll create a class for you with the relevant properties and amend the code so it now returns ObjectResult
you are selecting only one column value from statement which has varchar/string type, so this ObjectResult returns String.
I have checked that if selecting multiple column value in select statement then it returns ObjectResult and you can usee only required column value
I'm trying to create a stored proc for the first time, but I just can't get it right. So I have a proc which is returning a count from the db, based on the parameters being fed to it. I'm not sure what I'm doing wrong, if the SQL is wrong or if I'm mapping the function incorrectly. Here's my SQL:
USE [AuditTracker_Codegen]
GO
/****** Object: StoredProcedure [dbo].[GetAllFindingsCount] Script Date: 05/12/2016 08:43:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[GetAllFindingsCount](#ReportId int, #Priority int, #IsDeleted bit)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT COUNT(*)
from [dbo].[App_Finding] finding
WHERE finding.ReportId = #ReportId and finding.Priority = #Priority and finding.IsDeleted = #IsDeleted
END
First off, does this SQL query look right? I've executed it in SSMS and it seems to return the correct result.
I then go to VS, update model from database, add the stored procedure.
Then I go to Function Imports in Model Browser, right-click, Add Function Import. Select the stored proc from the dropdown list, click "Get Column Information", then press "Create New Complex Type". Give the thing a name, then press OK. As far as I know, that should be it, right? Or am I wrong?
In my code I then try
var context = new AuditTrackerDatabaseContext();
var findingsOne = context.GetAllFindingsCount_Result(report.ReportId,
(int) PriorityStatus.One, false).ToString();
And that's where I get the error above. When I check mapping details on the edmx for this proc, it says
Maps to GetAllFindingsCount Column
Column1 : Int32 <- Column1
Is anyone able to advise me on what I'm doing wrong here, why it's not working?
You probably need to give the count value a name, like this:
SELECT COUNT(*) AS RESULT_OF_COUNT
from ...
Working in VS2010 / C# - I have a form that shows data by using tableadaptor (ie from the drag & drop)
One of the fields in my database is booking.status. I have NOT displayed that field on the form.
The form takes variable bookingId and uses it to load a single record using the FillBy method.
The code for the save button is
this.bookingBindingSource.EndEdit();
this.bookingTableAdapter.Update(this.quick_quoteDataSet.booking);
Before this code executes, I would like to set the value of the status field to 'P'.
I can use this.bookingTableAdapter.Update() - but it seems I will have to read all of the values from the form and pass them into the update command along with the new value for the status field.
Is there a way I can simply amend the value of that one field for the current record?
Use Stored Procedure
USE [Assets]
GO
/****** Object: StoredProcedure [dbo].[UpdateAssDispRecord] Script Date: 12/15/2012 08:00:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[UpdateAssDispRecord]
#iDispID int,
#nDispno decimal,
#cKeygroup nchar(14),
#iCodeID int,
#dDate date,
#nSale decimal,
#nCumdep decimal,
#nBookvalue decimal,
#cRemarks nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
UPDATE ass_Disp
SET
nDispno=#nDispno,
cKeygroup=#cKeygroup,
iCodeID=#iCodeID,
dDate=#dDate,
nSale=#nSale,
nCumdep=#nCumdep,
nBookvalue=#nBookvalue,
cRemarks=#cRemarks
WHERE
iDispID = #iDispID
END
I am trying to use a stored procedure in Entity Framework that returns nothing.
I did the following:
Added a function (right click on stored procedure -> add -> function import-> Complex Type -> Get column information -> create New Complex-Type)
My function name: summarySP_Result. After building the project the entity class is not generated in Generated_code (BusinessAccount.web.g.cs)
But entity classes for tables and views are all created but nor for stored procedure.
Can anybody give the idea why it is not generated entity class in BusinessAccount.web.g.cs?
Update :
Let me confirm ReturnDataFromTemTable_result entity class created in your XXXXXX.web.g.cs class.
Like :
[DataContract(Namespace="http://schemas.datacontract.org/2004/07/BizFramework.Web.Model")]
public sealed partial class ReturnDataFromTemTable_Result : Entity
{
-------------------
}
OK - here's the step-by-step way of doing this:
(1) add your stored procedure to the EDMX file (when you first create it, or later on by using Update model from database and picking that stored procedure)
(2) once you have the stored procedure in your model - use the Model Browser to add a Function Import :
(3) the next dialog that pops up is vitally important - you need to (1) define that the stored procedure returns a collection of complex types, then you need to (2) get the column info from that stored procedure to know what columns it will return, then (3) you tell Visual Studio to generate a new complex type based on that column info:
(4) once you've done that - you should now see the stored procedure in your conceptual model section in the Model Browser, and the newly generated complex type should show up there, too:
This is for Ross Brigoli
Try adding this line to the beginning of your stored procedure:
SET FMTONLY OFF
You can remove this after you have finished importing.
Source:-
Why can't Entity Framework see my Stored Procedure's column information?
If this is still unresolved, after you Add the Function Import, go to the Solution Explorer, right click your {name}.Context.tt file and do "Run Custom Tool". The method will now show up in your derived Context class.
This seems like a bug in Visual Studio 2012, which is what I am using, I haven't applied Update 1, I will try to see if that fixes it.
As Sandeep said,
EF doesn't support importing stored procedures which build result set from Dynamic queries or Temporary tables.
But you don't have to rewrite your whole SP.
Just write another one, with the same name, that returns the correct row format without using dynamic SQL or a temp table. Then use the EF SP adding function, which will now auto generate the complex type.
Edit: It's actually easier to make a comment at the top of the SP that immediately selects the desired row with all the data types specified with CASTS. When you need to import the SP into EF, just uncomment the code.
e.g.
CREATE PROCEDURE myProc ()
AS
BEGIN
-- uncomment the following row to import:
-- SELECT CAST( 0 AS int) AS column1Name, CAST( 'a' AS varchar(50)) AS clumn2name
-- comment out the SP content when you want to import it.
< proper SP content >
END
Then drop the stored proc and create the original.
Save this temporary importing SP you have made in case you need it again, though.
EF doesn't support importing stored procedures which build result set from:
Dynamic queries
Temporary tables
Re-write your stored procedure to use a table variable instead.
remember to drop the stored procudure and function import from your model before updating as it wont generate the complex type unless it also adds the stored procedure. or go to function import properties and use the get column information feature after updating your stored procedure.
create procedure [dbo].[usp_InsertOrUpdate]
/*if your table(tbl_InsertOrUpdate) as 3 columns like uniqueid,col1,col2*/
#uniqueId bigint NULL,/*if insert send value as null or 0*/
#col1 bigint null,
#col2 [varchar](500) NULL
as
begin
set nocount ON
SET FMTONLY OFF
/* for giving result which column updated(uniqueId) and is it insert or update(IsInsert)*/
declare #varResult table (uniqueId bigint ,IsInsert bit )
/*create a var table before inserting original table*/
declare #varInsertOrUpdate table (
uniqueId bigint ,
col1 [bigint] ,
col2 [varchar]
)
/*default we are feel as update only*/
insert into #varResult (uniqueId,IsInsert) values (#uniqueId,0)
/*insert into var table*/
INSERT INTO #varInsertOrUpdate (uniqueId,col1,col2)
VALUES
(#uniqueId,#col1,#col2)
/*Insert into original table with where condition without if else*/
INSERT INTO tbl_InsertOrUpdate (col1,col2)
select col1,col2 from #varInsertOrUpdate
where uniqueId!=0;
/*if its insert updating result returning table*/
update #varResult set
uniqueId=IDENT_CURRENT('tbl_InsertOrUpdate'),
IsInsert=1 where #uniqueId=0;
/*updating table where #uniqueid is null or empty*/
UPDATE tbl_InsertOrUpdate
SET col1=#col1,
col2=#col2,
WHERE uniqueId=#uniqueId and #uniqueId!=0
select * from #varResult
end
To add complex type correctly, go Model browser, right click on function, then display edit, click edit an fill the dialog box. The name of the function should be same as name of the stored procedure. Click OK button. Now function is created. Then right click on the created function and go edit again.There is a update button aside of complex type button.Update it using that update button. Now complex type is created completely.
This is my SP to Implement the multiple search
***************************************************
CREATE PROCEDURE [dbo].[uspSEARCH_POSITIONS]
#OBJ_TYPE_REQUEST varchar(2000),--'FIRST_NAME;SEARCHVALUE|LAST_NAME;SEARCHVALUE|JOB_DESCRIPTION;SEARCHVALUE'
#DELIMITER varchar(10) --'| Which seperates the col;searchvalue|col;searchvalue
AS
BEGIN
SET FMTONLY OFF
DECLARE
#lLastName varchar(100),
#lFirstName varchar(100),
#lPositionNumber varchar(20),
#lJobDescription varchar(50),
#lJobCode varchar(20),
#lOccupancyIndicator varchar(50),
#ldeleimitercolsearchval varchar(10)
SET #ldeleimitercolsearchval =';'
CREATE TABLE #TempTable (ColSearchValues VARCHAR(2000))
INSERT INTO #TempTable
SELECT * FROM [dbo].[fnSplit](#OBJ_TYPE_REQUEST,#DELIMITER)--'fname;searchvalfname|lname;searchvallname|jobcode;searchvaljobcode','|')
SELECT #lLastName=SUBSTRING(ColSearchValues,CHARINDEX(#ldeleimitercolsearchval ,ColSearchValues)+1,LEN(ColSearchValues)) from #TempTable where lower(ColSearchValues) like '%last%'
SELECT #lFirstName =SUBSTRING(ColSearchValues,CHARINDEX(#ldeleimitercolsearchval ,ColSearchValues)+1,LEN(ColSearchValues)) from #TempTable where lower(ColSearchValues) like '%first%'
SELECT #lPositionNumber =SUBSTRING(ColSearchValues,CHARINDEX(#ldeleimitercolsearchval ,ColSearchValues)+1,LEN(ColSearchValues)) from #TempTable where lower(ColSearchValues) like '%position%'
SELECT #lJobDescription=SUBSTRING(ColSearchValues,CHARINDEX(#ldeleimitercolsearchval ,ColSearchValues)+1,LEN(ColSearchValues)) from #TempTable where lower(ColSearchValues) like '%jobd%'
SELECT #lJobCode=SUBSTRING(ColSearchValues,CHARINDEX(#ldeleimitercolsearchval ,ColSearchValues)+1,LEN(ColSearchValues)) from #TempTable where lower(ColSearchValues) like '%jobc%'
SELECT #lOccupancyIndicator=SUBSTRING(ColSearchValues,CHARINDEX(#ldeleimitercolsearchval ,ColSearchValues)+1,LEN(ColSearchValues)) from #TempTable where lower(ColSearchValues) like '%ccupancy%'
SELECT [PS].[POSITION_NUMBER]
,[PS].[COST_CENTER]
,[PS].[JOB_CODE]
,[PS].[JOB_CODE_DESCRIPTION]
,[PS].[SITE_CODE]
,[EMP].[EMPLOYEE_ID]
,[EMP].[EIN]
,[EMP].[GRADE]
,[EMP].[LOGIN_ID]
,[EMP].[FIRST_NAME]
,[EMP].[LAST_NAME]
,LTRIM(RTRIM(ISNULL([EMP].[LAST_NAME],''))) + ',' +LTRIM(RTRIM(ISNULL([EMP].[FIRST_NAME],''))) AS [FULL_NAME]
,[EMP].[DISTRICT]
,[EMP].[SUPERVISOR_EIN]
,COUNT(*) OVER() AS TOTAL_RECORD_COUNT
FROM [DBSERVER].[dbo].[uvwPOSITION_SEARCH] PS
LEFT JOIN [DBSERVER].[dbo].[uvwEMPLOYEES] EMP
ON PS.POSITION_NUMBER=EMP.POSITION_NUMBER
WHERE
(#lLastName IS NULL OR [LAST_NAME] LIKE '%' + #lLastName + '%')
AND (#lFirstName IS NULL OR [FIRST_NAME] LIKE '%' + #lFirstName + '%')
AND (#lPositionNumber IS NULL OR [PS].[POSITION_NUMBER] LIKE '%' + #lPositionNumber + '%')
AND (#lJobDescription IS NULL OR [PS].[JOB_CODE_DESCRIPTION] LIKE '%' + #lJobDescription + '%')
AND (#lJobCode IS NULL OR [PS].[JOB_CODE] LIKE '%' + #lJobCode + '%')
AND (#lOccupancyIndicator IS NULL OR [EMP].[FILLED_VACANT] LIKE '%' + #lOccupancyIndicator + '%')
END
Now you can consume above SP in edmx using below
Adding stored procedures complex types in Entity Framework
Why can't Entity Framework see my Stored Procedure's column information?
And in case you have to update your SP below worked for me.
Updating Complex Type if Stored Procedure Updates
How Do I Get Entity Framework To Update Complex Types?
For me, Im having problems where importing my Stored Procedure into EF is not generating the Complex Entity return object (automatically). I found however, after commenting out sections of my sproc (aka stored procedure), that when I then re-imported the stored procedure back in (ie refreshed using the Get Column Information button in the Function Import Edit screen), that the Complex type could then be generated!
In short, there could be a where clause (or maybe something else) causing EF to not generate the Complex Type. Try commenting out sections of your sproc and re-importing the sproc to
UPDATE:
Further to my investigation above, I found that the reason the Complex Entity was not being generated was because my sproc was using a view (instead of a typical table). For curiosity sake, I changed the view to another table just to see what would happen, and the complex entity generated.
So, in short, it looks like Complex Entities might not generate automatically if you have a view. To try, I ripped out the view temporarily, re-import the sproc, generated the Complex Entity, then put the view back in. But now my code gives exceptions.
Will update on this later when I learn more =)
UPDATE:
Fixed the issue. Really silly mistake! The viewname that I was using was not spelled right =D. Im sort of angry that an error wasnt thrown by Sql Server when I created the sproc..... I guess that is life :) Alas, problem now fixed!
The issue of complex type not appearing may happen due to a different reason as well which is what I faced in our case. The issue was due to a syntax error in the SPROC where temp table was defined as below -
create table #temp(
col1 int,
col2 nvarchar(100),
col3 nvarchar(100), -- Notice the comma in the end
);
Surprisingly, SQL Server doesn't throw any error when you compile the sproc. Removing the comma fixed the problem for us.
In short, while some of the above solutions might work depending on the specific issue, my suggestion is to check your sproc for such syntactical errors that SQL might ignore but could be the underlying reason for this problem. Thanks.
Go to the Model Browser
If you need to modify existing function
Under the Function Imports >> Select the function to be modified >> Click Edit
You will need to update the function to refresh and you can see the columns need to be added