I have got 2 asp pages. Firstly i get logged in through log in page and 2nd page is home page where i got few buttons of some tasks. Along with that i got user details which consists of FULLNAME,ADDRESS,CELL NUMBER,BLOOD GROUP and EMAILID, this should be displayed dynamically in their particular labels from DATABASE once the user logs in using his username and password.
I have written Query for this within the GetLoginDetails Stored Procedure. I have to display Employee Name,his Last Login Date,Time etc. once his log in and enters home page in the same way i should get user details.
ALTER PROCEDURE [dbo].[GetLastLogin]
#LoggedInUser nvarchar(50),
#FullName nvarchar(50),
#Address nvarchar(50),
#MobileNumber bigint,
#EmailID nvarchar(50),
#BloodGroup nvarchar(50),
#EmpName nvarchar(50)
As
Declare #LastLogin int
Set #LastLogin = (Select MAX(AccessID)from dbo.ACCESS_INFO where Flag = 1)
Select Access_Date, Access_Time from dbo.ACCESS_INFO where LoggedInUser = #LoggedInUser and AccessID = #LastLogin
Update dbo.EmployeeData
Set Empname = #EmpName
where FullName = #FullName and Address = #Address and MobileNumber = #MobileNumber and EmailID = #EmailID and BloodGroup = #BloodGroup ;
im getting error saying tht ("Procedure or function 'GetLastLogin' expects parameter '#FullName', which was not supplied.") please help me out
back end code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Username"] != null)
{
try
{
MTMSDTO objc = new MTMSDTO();
LblLogdInUser.Text = Session["EmpName"].ToString();
LblUser.Text = Session["Username"].ToString();
objc.LoggedInUser = LblUser.Text;
DataSet laslogin = obj.GetLastLogin(objc);
DataView LasLogin = new DataView();
LasLogin.Table = laslogin.Tables[0];
GrdLasLogin.DataSource = LasLogin;
GrdLasLogin.DataBind();
if (!IsPostBack)
{
int lastlog = GrdLasLogin.Rows.Count;
if (lastlog == 0)
{
LblLastLoginD.Text = "This is your First Login";
DateTime today = System.DateTime.Now.Date;
LblToday.Text = today.ToString();
LblTime.Text = System.DateTime.Now.ToLongTimeString();
objc.LoggedInUser = LblLogdInUser.Text;
objc.AccessDate = Convert.ToDateTime(LblToday.Text);
objc.AccessTime = Convert.ToDateTime(LblTime.Text);
objc.AccessStatus = "New Login";
objc.AccessFlag = 1;
int accessinfo = obj.InsertAccessInfo(objc);
}
else
{
LblLastLoginD.Text = Convert.ToDateTime(GrdLasLogin.Rows[0].Cells[0].Text).ToString("dd/MMM/yyyy");
LblLastLoginT.Text = GrdLasLogin.Rows[0].Cells[1].Text;
DateTime today = System.DateTime.Now.Date;
LblToday.Text = today.ToString();
LblTime.Text = System.DateTime.Now.ToLongTimeString();
objc.LoggedInUser = LblLogdInUser.Text;
objc.AccessDate = Convert.ToDateTime(LblToday.Text);
objc.AccessTime = Convert.ToDateTime(LblTime.Text);
objc.AccessStatus = "New Login";
objc.AccessFlag = 1;
int accessinfo = obj.InsertAccessInfo(objc);
}
LblFname.Visible = true;
LblAdd.Visible = true;
LblMnum.Visible = true;
LblMailID.Visible = true;
LblBGroup.Visible = true;
}
}
catch (Exception ex)
{
Response.Redirect("ERROR.aspx");
Session.Abandon();
}
}
else
{
Response.Redirect("~/Login.aspx");
}
Response.CacheControl = "no-cache";
}
The error message makes it clear that you need to supply values for the parameter FullName. So, if you aren't already doing that, then go do that. The only complication here is null values; a string can be null, but to specify that in ADO.NET you need to pass DBNull.Value; if you use null the parameter is not included. This means you end up with code like:
cmd.Parameters.AddWithValue("FullName", (object)fullName ?? DBNull.Value);
Ugly, but it works.
Alternatively, many helper utilities will do this for you. So with "dapper":
var lastAccess = conn.Query<AccessInfo>("GetLastLogin",
new { LoggedInUser = cn, FullName = fullName, /* snipped */ },
commandType: CommandType.StoredProcesdure).FirstOrDefault();
The problem is not in your SQL. It's in your calling function in asp. You are not sending the fullname parameter to SQL server correctly. Check out this question for an example on how to send parameters.
Call a stored procedure with parameter in c#
Related
I have a listbox with a list of items that get loaded when you navigate to a certain page. Then I have an on click that passes parameters to an AddProducts method. That method is what loops through all selected items and inserts values from the fields filled in as well as takes the values from the listItems and adds them as parameters to a stored procedure.
The problem I'm running into is that when looping through the listItems
if(selectedItem.Selected) is returning false, but in my method where I load the listbox I initialize a SelectedValue so I'm not sure why it's giving me the error message I have for no selected items. I was able to get it to work yesterday before I moved LoadListBoxCategories outside of LoadAddData but unsure as to why that would have any effect to if(listItem.Selected).
I'm relatively new to asp.net so any help/ explanation as to why my code isn't working is extremely appreciated. I've spent the last three days trying to figure this out and haven't found a solution that works.
Code:
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session[IS_LOGGED_IN] == null)
{
Response.Redirect("/utilities/companydata/login.aspx", true);
return;
}
gvTextInputs.RowEditing += new GridViewEditEventHandler(gvTextInputs_RowEditing);
if (!IsPostBack)
{
string pageId = Request.QueryString["pageid"];
string productId = Request.QueryString["productid"];
/* Add Mode */
if (!string.IsNullOrEmpty(pageId))
{
SetMode(MODE_ADD, "");
LoadAddData(pageId);
LoadListBoxCategories(pageId);
}
else if (!string.IsNullOrEmpty(productId))
{
string imageServer;
if (LoadProductData(productId, out imageServer))
{
InitImageGridview();
InitTextGridview();
InitStaticGridview();
SetMode(MODE_EDIT, imageServer);
SetImageServer(imageServer);
}
else
{
//TO DO - Return Error
}
}
}
else
{
InitImageGridview();
InitTextGridview();
InitStaticGridview();
}
}
Load ListBox:
private void LoadListBoxCategories(string pageId)
{
listBoxCategories.Visible = true;
//This gets query is so I can store the CompanyId and the CombinedValue data from pageId
string select = "SELECT companyName, cl.GbsCompanyId, cl.companyId, wpt.productTypeId, productName, (CAST(wp.pageId as varchar(200)) +'|'+ CAST(wp.productTypeId as varchar(200)) + '|' ) AS CombinedValue FROM CompanyList cl, WtpPages wp, WtpProductTypes wpt WHERE cl.companyId=wp.companyId AND wpt.productTypeId=wp.productTypeId AND wp.pageId=#pageId";
SqlDataSource connectionId = new SqlDataSource(DB_CONNECT, select);
connectionId.SelectParameters.Add("pageId", pageId);
DataView dView = (DataView)connectionId.Select(DataSourceSelectArguments.Empty);
if (dView.Table.Rows.Count == 1)
{
string companyId = dView.Table.Rows[0]["companyId"].ToString();
string curCategoryProductTypeId = dView.Table.Rows[0]["CombinedValue"].ToString();
// EXEC MCAdmin_GetAllCategoriesByCompanyId #companyId
// Lists All Categories #companyId has Active
string selectLoadData = "EXEC MCAdmin_GetAllCategoriesByCompanyId #companyId";
SqlDataSource conn = new SqlDataSource(DB_CONNECT, selectLoadData);
conn.SelectParameters.Add("companyId", companyId);
lstCategoriesBox.Items.Clear();
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
// Pre-selects the value of the productTypeId you are trying to add a product for
// to send later run against a foreach insert in AddProduct()
lstCategoriesBox.SelectedValue = curCategoryProductTypeId;
testOutcomeCategory.InnerText = curCategoryProductTypeId;
lstCategoriesBox.DataSource = conn;
lstCategoriesBox.DataBind();
}
}
AddProduct:
private string AddProduct(string companyId, out string errMsg)
{
foreach (ListItem selectedItem in lstCategoriesBox.Items)
{
if (selectedItem.Selected)
{
// assign current productTypeId & pageId from selected Categories new CombinedValue column
string[] splitColumnValue = selectedItem.Value.Split('|');
string selectedPageId = splitColumnValue[0].ToString();
string selectedProductTypeId = splitColumnValue[1].ToString();
SqlDataSource connnection = new SqlDataSource(DB_CONNECT, "");
connnection.InsertCommand = "EXEC MCAdmin_AddProductFromClassic #pageId, #productTypeId, #productCode, #imgDirectory, #numSides, #sortOrder, #isActive, #template, #template2, #template3, #EditorJson, #MockupTemplateBase, #MockupTemplateTreatment, #BorderDefault ";
connnection.InsertParameters.Add("pageId", selectedPageId);
connnection.InsertParameters.Add("productTypeId", selectedProductTypeId);
connnection.InsertParameters.Add("productCode", txtProductCode.Text);
connnection.InsertParameters.Add("numSides", ddlNumSides.SelectedValue);
connnection.InsertParameters.Add("sortOrder", txtSortOrder.Text);
connnection.InsertParameters.Add("isActive", ddlActive.SelectedValue);
connnection.InsertParameters.Add("template", txtTemplate1.Text);
connnection.InsertParameters.Add("template2", txtTemplate2.Text);
connnection.InsertParameters.Add("template3", txtTemplate3.Text);
connnection.InsertParameters.Add("EditorJson", txtJson.Text);
connnection.InsertParameters.Add("MockupTemplateBase", txtMockupTemplateBase.Text);
connnection.InsertParameters.Add("MockupTemplateTreatment", txtMockupTemplateTreatment.Text);
connnection.InsertParameters.Add("BorderDefault", txtBorderDefault.Text);
/* Special Product Code for Upload Artwork Business Card */
if (txtProductCode.Text.ToUpper() == "BPFAH1-001-100")
{
connnection.InsertParameters.Add("imgDirectory", "/images/business-cards/general/");
}
else
{
connnection.InsertParameters.Add("imgDirectory", ddlImgDir.SelectedValue);
}
int result = connnection.Insert();
if (result > 0)
{
SqlDataSource connect = new SqlDataSource(DB_CONNECT, "");
connect.SelectCommand = "SELECT TOP 1 wtpProductId FROM WtpProducts ";
connect.SelectCommand = "WHERE productTypeId=#productTypeId AND pageId=#pageId DESC ";
connect.SelectParameters.Add("pageId", selectedPageId); //
connect.SelectParameters.Add("productTypeId", selectedProductTypeId); //
DataView dView = (DataView)connect.Select(DataSourceSelectArguments.Empty);
if (dView.Table.Rows.Count == 1)
{
string wtpProductId = dView.Table.Rows[0]["wtpProductId"].ToString();
errMsg = "";
return wtpProductId;
}
else
{
errMsg = "ERROR: Could not get productId of newly created Product.";
return "0";
}
}
else
{
errMsg = "ERROR: Could not add WtpProduct record to DB";
return "0";
}
}
else
{
errMsg = "ERROR: You must select a Category";
return "0";
}
}
errMsg = "ERROR: Did not make it into the foreach loop";
return "0";
}
OnClick method:
protected void OnClick_btnAddProduct(object sender, EventArgs e)
{
string pageId = Request.QueryString["pageid"];
testOutcomeCategory.InnerText = lstCategoriesBox.SelectedValue; // This proves that I have something selected!!!
string select = "SELECT companyName, cl.GbsCompanyId, cl.companyId, wpt.productTypeId, productName, baseImgDirectory, templateDirectory, wp.imageServer FROM CompanyList cl, WtpPages wp, WtpProductTypes wpt WHERE cl.companyId=wp.companyId AND wpt.productTypeId=wp.productTypeId AND wp.pageId=#pageId";
SqlDataSource conn = new SqlDataSource(DB_CONNECT, select);
conn.SelectParameters.Add("pageId", pageId);
DataView dView = (DataView)conn.Select(DataSourceSelectArguments.Empty);
if(dView.Table.Rows.Count == 1)
{
string companyId = dView.Table.Rows[0]["companyId"].ToString();
if (!string.IsNullOrEmpty(pageId))
{
string errMsg;
string productId = AddProduct(companyId, out errMsg);
if(productId != "0")
{
Response.Redirect("/utilities/companydata/add-edit-wtp-product.aspx?productid=" + productId, true);
SetStatusMsg("Success", false);
}
else
{
SetStatusMsg(errMsg, true);
}
}
}
}
The list box instance is recreated on the server-side during the postback (as well as entire page). You do not set the selected items in the Page_Load event handler - if (!IsPostBack) goes to else branch. This is why you don't see them.
Ok,
lstCategoriesBox.Items.Clear();
Ok, above goes nuclear - blows out the list, blows out the selection.
Ok, that's fine
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
Ok, above adds a new item. Should be ok, but one should setup the lb BEFORE adding any data - including that "--select--" row.
It just makes sense to "setup" the lb and THEN start adding data, right?
However, But, if above works - ok, then lets keep going, but I would setup the lb before adding any rows of data. Say like this:
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
Now, the next line:
lstCategoriesBox.SelectedValue = curCategoryProductTypeId;
Ouch! - we just cleared the lb, and now we trying to set it to a value? You can't do that - the lb just been cleared, right? You would need to load up the lb first, and THEN you can set it to the selected value, right?
I might be missing something here, but that lb needs to be loaded up with valid data BEFORE you attempt to set the selected value?
To test first, change following
Outcome Category.InnerText = list CategoriesBox.SelectedValue;
to
Category.InnerText = Request.Form["CategoriesBox-ClientID"]
If the data is coming in correctly, the list view cleared or reloaded when between reload and click events the page.
UPDATE: I just figured it out! So stupid but when I check if(selectedItem.Selected) since I'm looping through the ListBox items it starts at the first index of the ListBox and since the first isn't selected then that if goes to the else block. Remove the else and it works fine
Can anyone help me with problem with trigger on insert/update when inserting records to tables in a SQL Server database using EF and TransactionScope?
When I try the trigger in SQL Server Management Studio, it's working fine, also the app is working fine when there is no trigger or trigger is disabled.
I have 2 SQL Server tables, Orders and OrdersParts. I have a trigger on OrdersParts that I use to update another table based calculations of inserted records.
Is any workaround so I can make something in SQL Server trigger because I don't want to change the code?
Thank you...
Here is my code in VS, I get fail in repository.CreateOrder
public void CreateOrder(Guid userId, int? referenceId, Cart cart, OrderInfo orderInfo)
{
using (TransactionScope transaction = new TransactionScope())
{
var order = new Orders
{
UserId = userId,
ReferenceId = referenceId,
Status = (int)OrderStatus.Created,
PaymentType = (int)orderInfo.PaymentType,
ShippingType = orderInfo.ShippingType,
Comment = orderInfo.Comment,
DateTimeCreated = DateTime.Now
};
context.Orders.Add(order);
context.SaveChanges();
foreach (var line in cart.Lines)
{
context.OrdersParts.Add(new OrdersParts
{
PartId = line.Product.ProductId,
OrderId = order.OrderId,
Price = line.Product.Price,
Quantity = line.Quantity
});
}
context.SaveChanges();
transaction.Complete();
}
}
Here is My CreateOrder HTTP Post Method:
[HttpPost]
public ActionResult CreateOrder(Cart cart, OrderInfo orderInfo)
{
var result = new JsonResult<bool>() { Status = true };
var user = Membership.GetUser(User.Identity.Name);
var userId = (Guid)user.ProviderUserKey;
try
{
var userDetails = usersRepository.Members.FirstOrDefault(x => x.UserId == userId);
if (!userDetails.ClientId.HasValue)
{
result.Status = false;
result.Result = false;
result.Message = "Errror Client";
return Json(result);
}
int clientId = userDetails.ClientId.Value;
// Create order in WareHouse
string message = null;
int? referenceId;
if (!integrationService.CreateOrder(clientId, cart, orderInfo, out referenceId, out message))
{
result.Status = false;
result.Result = false;
result.Message = message;
return Json(result);
}
repository.CreateOrder(userId, referenceId, cart, orderInfo);
cart.Clear();
result.Result = true;
result.Message = "";
}
catch
{
result.Status = false;
result.Result = false;
result.Message = "Error on creating order! Please try again.";
}
return Json(result);
}
Trigger:
ALTER TRIGGER [dbo].[UpdateComment] ON [dbo].[OrdersParts]
WITH EXECUTE AS CALLER
AFTER INSERT, UPDATE
AS
BEGIN
DECLARE #OrderID INT;
DECLARE #QDefWareH INT;
DECLARE #OrderedQuantity INT;
DECLARE #ArticleID VARCHAR(20);
DECLARE my_Cursor CURSOR FAST_FORWARD
FOR
SELECT a.OrderId ,
a.Quantity ,
b.RefSifra
FROM INSERTED a
LEFT OUTER JOIN dbo.Accounting b ON b.PartId = a.PartId;
OPEN my_Cursor;
FETCH NEXT FROM my_Cursor INTO #OrderID, #OrderedQuantity, #ArticleID;
EXEC #QDefWareH = _SPArtInDefWarehouse #ArticleID;
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #QDefWareH;
IF ( #OrderedQuantity > #QDefWareH )
BEGIN
UPDATE dbo.Orders
SET Comment = IIF(Comment IS NULL, #ArticleID, Comment
+ ' ;' + CHAR(13) + CHAR(10) + #ArticleID)
WHERE OrderId = #OrderID;
END;
FETCH NEXT FROM my_Cursor INTO #OrderID, #OrderedQuantity,
#ArticleID;
END;
CLOSE my_Cursor;
DEALLOCATE my_Cursor;
END;
I was getting a :There is no row at position 0 previously.On debugging i noticed the Count of Table Select_By_SNAME_BLOCKNO is 0 .
Also when i placed breakpoint ,on some columns i am getting Cannot evaluate expression because the code of the current method is optimized error .
So what is going wrong here?
Here is the block of code where error is received :
DS_HOUSE.HOUSE_SELECTDataTable HDT = new DS_HOUSE.HOUSE_SELECTDataTable();
DS_HOUSETableAdapters.HOUSE_SELECTTableAdapter HAdapter = new DS_HOUSETableAdapters.HOUSE_SELECTTableAdapter();
DS_USER.USERMST_SELECTDataTable UDT = new DS_USER.USERMST_SELECTDataTable();
DS_USERTableAdapters.USERMST_SELECTTableAdapter UAdapter = new DS_USERTableAdapters.USERMST_SELECTTableAdapter();
protected void Page_Load(object sender, EventArgs e)
{
lblsell.Text = "";
UDT = UAdapter.Select_By_UID(Convert.ToInt32(Session["uid"].ToString()));
HDT = HAdapter.Select_By_SNAME_BLOCKNO(UDT.Rows[0]["societyname"].ToString(), Convert.ToInt32(UDT.Rows[0]["HID"].ToString()));
ViewState["HID"] = HDT.Rows[0]["HID"].ToString();
lblbno.Text = HDT.Rows[0]["blockno"].ToString();
lbltype.Text = HDT.Rows[0]["type"].ToString();
lblsname.Text = HDT.Rows[0]["sname"].ToString();
Image3.ImageUrl = HDT.Rows[0]["image"].ToString();
}
Here is the defintion of Select_By_SNAME_BLOCKNO
public virtual DS_HOUSE.HOUSE_SELECTDataTable Select_By_SNAME_BLOCKNO(string sname, global::System.Nullable<int> bno) {
this.Adapter.SelectCommand = this.CommandCollection[5];
if ((sname == null)) {
this.Adapter.SelectCommand.Parameters[1].Value = global::System.DBNull.Value;
}
else {
this.Adapter.SelectCommand.Parameters[1].Value = ((string)(sname));
}
if ((bno.HasValue == true)) {
this.Adapter.SelectCommand.Parameters[2].Value = ((int)(bno.Value));
}
else {
this.Adapter.SelectCommand.Parameters[2].Value = global::System.DBNull.Value;
}
DS_HOUSE.HOUSE_SELECTDataTable dataTable = new DS_HOUSE.HOUSE_SELECTDataTable();
this.Adapter.Fill(dataTable);
return dataTable;
}
Also stored procedure Select_By_SNAME_BLOCKNO code is :
create procedure Select_By_SNAME_BLOCKNO
#sname nvarchar(50),
#bno int
AS
BEGIN
select * from dbo.HouseMst where Sname=#sname and blockno=#bno
This returns the values but i am not able to retrieve on page.
I'm trying to put an ALL search function for my aspx page. The problem is that I have no idea how to do it properly. This is as far as I can go, here's the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dtTransactionCategory = clsTransactionCategory.GetTransactionCategory(Helper.LogID, Helper.OrgID, Helper.SiteID, 0, string.Empty);
ddlTransactionCategoryDesc.DataSource = dtTransactionCategory;
ddlTransactionCategoryDesc.DataTextField = "TransactionCategoryDesc";
ddlTransactionCategoryDesc.DataValueField = "TransactionCategoryID";
ddlTransactionCategoryDesc.DataBind();
ddlTransactionCategoryDesc.Items.Insert(0, new ListItem("All"));
ddlTransactionCategoryInput.DataSource = dtTransactionCategory;
ddlTransactionCategoryInput.DataTextField = "TransactionCategoryDesc";
ddlTransactionCategoryInput.DataValueField = "TransactionCategoryID";
ddlTransactionCategoryInput.DataBind();
logID = CommonFunctions.StringToInt(Session[Constants.SessionLogID].ToString());
orgID = 1;
siteID = 1;
ddlTransactionCategoryDesc.SelectedValue = Convert.ToString(ddlTransactionCategoryDesc);
txtTransactionDesc.Text = string.Empty;
BindData();
}
}
and the stored procedure, should it needed:
ALTER PROC [dbo].[spMSTransaction_Get]
#OrgID INT,
#SiteID INT,
#TransactionCategoryID INT,
#TransactionCategoryDesc varchar (300),
#TransactionDesc varchar(300)
AS
SET NOCOUNT ON
SELECT mst.[OrgID],
mst.[SiteID],
mst.[TransactionID],
mst.[TransactionCategoryID],
mstc.[TransactionCategoryDesc],
mst.[TransactionDesc],
mst.[IsActive],
[master].dbo.fnConvertUTCToLocalTimeZone (mst.[CreatedDate]) as [CreatedDate],
mst.[CreatedBy],
[master].dbo.fnConvertUTCToLocalTimeZone (mst.[ModifiedDate]) as [ModifiedDate],
mst.[ModifiedBy]
FROM [dbo].[MSTransaction] AS mst
INNER JOIN [dbo].[MSTransactionCategory] AS mstc
ON mst.OrgID = mstc.OrgID AND mst.SiteID = mstc.SiteID AND mst.TransactionCategoryID = mstc.TransactionCategoryID
WHERE (mst.[OrgID] = #OrgID OR #OrgID = 0)
AND (mst.[SiteID] = #SiteID OR #SiteID = 0)
AND (mst.[TransactionCategoryID] = #TransactionCategoryID OR #TransactionCategoryID = 0)
AND (mst.[TransactionDesc] LIKE '%' + #TransactionDesc + '%')
AND (mst.[isActive] = 1)
I already put ddlTransactionCategoryDesc.Items.Insert(0, new ListItem("All")); but it returned an error:
Input string was not in a correct format.
Any idea what I need to fix and what I should do to make the ALL search function? Thanks.
According to your Stored Procedure, #TransactionCategoryID is an INT. Adding the ALL list will require you use the following instead:
ddlTransactionCategoryDesc.Items.Insert(0, new ListItem("All", "0"));
This will make the value of ALL to be an INT. What you currently have - ListItem("All") automatically changes the type of the Value to a string. Check your dropdown after execution, it will show the value as All but that cannot be passed into the INT that the Stored Proc requires.
I get this error after I've imported a stored procedure then create a complex type and name the function import "sproc_Forums_GetForumGroupByID" this procedure gets a single forum from a ObjectDataSource once the GridView is selected. I get the error on the line of the ExecuteReader. I already have one stored procedure working with the entity framework and it works perfectly I don't understand whats going wrong when I started my second procedure
The EntitySet 'sproc_Forums_GetForumGroupByID' is not defined in the EntityContainer 'CMSEntities'. Near simple identifier, line 1, column 13.
public class Forums
{
public Forum GetForumGroup(int ForumGroupID)
{
using (EntityConnection conn = new EntityConnection("name=CMSEntities"))
{
conn.Open();
EntityCommand cmd = new EntityCommand("CMSEntities.sproc_Forums_GetForumGroupByID", conn);
cmd.Parameters.AddWithValue("ForumGroupID", ForumGroupID);
using (EntityDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
/*
Forum forum = null;
int forumID = (int)reader[0];
string addedBy = reader[1].ToString();
DateTime addedDate = (DateTime)reader[2];
string title = reader[3].ToString();
string updatedBy = reader[4].ToString();
DateTime updatedDate = (DateTime)reader[5];
bool active = (bool)reader[6];
forum = new Forum(forumID, addedBy, addedDate, title, "", 0, 0, false, "",
updatedBy, updatedDate, active, "", 0, "", DateTime.Now, "");
return forum;*/
}
return null;
}
}
}
Verify that the sp exists in the database.
Update the entity model.
use 'Import Function' in your model browser to import stored procedure.
As a sidenote, I usually use my stored procedures as following.
IMO it's simpler than using EntityDataReader.
public Forum GetForumGroup(int forumGroupID)
{
using(CMSEntities cmsContext = new CMSEntities())
{
var forum = cmsContext.sproc_Forums_GetForumGroupByID(forumGroupID);
//...
}
}