I am using asp.net with a c# back end to create a job website with a master and detail view.
To pull data I am using entity framework that was reverse engineered code first from a SQL server 2005 instance running on the same xp machine that I am doing development on. I would like the detail view on the website to be able view and edit existing records selected on the master view, but also be able to insert records.
So far I gotten to the point where the detail view can be used both view and insert records but editing has been unsuccessful as of yet. I don't get an error on update, and the I see no change reflected anywhere.
Some of the solutions I've seen say that you have to have DataKeyNames defined. (In my case I have used a field: Job_UID, which is actually how I connected the detail and master views.)
I have tried to made sure that I have the update query defined properly by reducing the number of items in the where clause to just reflect my PK and also by testing the query in the query designer.
Here are my queries:
SelectCommand="SELECT Job_Details.Job_UID, Job_Details.Job_Title, Job_Details.Job_Store_ID, Job_Details.Job_Type_Id, Job_Details.Job_Description, Job_Details.Job_Responsibilities, Job_Details.Job_Pay, Job_Details.Job_Supervisor, Job_Details.Job_Start_Date, Job_Details.Job_End_Date, Job_Details.Job_Meta_Post_StartDate, Job_Details.Job_Meta_Post_EndDate, Job_Details.Job_Meta_Keywords, Store_Look_Up.Store_Name, Store_Look_Up.Store_Region, Store_Look_Up.Store_Address, Job_Type.Job_Type_Name, Job_Type.Job_Type_Description FROM Job_Details INNER JOIN Job_Type ON Job_Details.Job_Type_Id = Job_Type.Job_Type_Id INNER JOIN Store_Look_Up ON Job_Details.Job_Store_ID = Store_Look_Up.Store_Id WHERE (Job_Details.Job_UID = #Job_UID)"
InsertCommand="INSERT INTO Job_Details(Job_UID, Job_Title, Job_Store_ID, Job_Type_Id, Job_Description, Job_Responsibilities, Job_Pay, Job_Supervisor, Job_Start_Date, Job_End_Date, Job_Meta_Post_StartDate, Job_Meta_Post_EndDate, Job_Meta_Keywords) VALUES (#Job_UID, #Job_Title, #Job_Store_ID, #Job_Type_Id, #Job_Description, #Job_Responsibilities, #Job_Pay, #Job_Supervisor, #Job_Start_Date, #Job_End_Date, #Job_Meta_Post_StartDate, #Job_Meta_Post_EndDate, #Job_Meta_Keywords)"
UpdateCommand="UPDATE Job_Details SET Job_Title = #Job_Title, Job_Store_ID = #Job_Store_ID, Job_Type_Id = #Job_Type_Id, Job_Description = #Job_Description, Job_Responsibilities = #Job_Responsibilities, Job_Pay = #Job_Pay, Job_Supervisor = #Job_Supervisor, Job_Start_Date = #Job_Start_Date, Job_End_Date = #Job_End_Date, Job_Meta_Post_StartDate = #Job_Meta_Post_StartDate, Job_Meta_Post_EndDate = #Job_Meta_Post_EndDate, Job_Meta_Keywords = #Job_Meta_Keywords WHERE (Job_UID = #Original__Job_UID)">
The rest of the solutions I've seen seem to involve a lot of custom coding. Shouldn't there be a way to do this just using Visual Studio's code generator, with some coding tweaks?
Any help would be appreciated, and thanks in advance!
The problem was with my update command:
I used the ItemUpdatedEvent of my FormView to determine how many rows were modified: 0 in my case.
string textToDisplay = string.Empty;
textToDisplay += "AffectedRows: " + e.AffectedRows.ToString() + "|";
Label1.Text = textToDisplay;
Once I was clearly able to see how many rows were being updated, I proceeded to test the query. I replaced #Original_Job_UID with the PK. And it worked on the page.
Then I looked through some MSDN documentation and saw that the filter should have been
#Job_UID. I entered it and it worked!
Hope this helps you!
Related
I have a database with three tables in it. I created all the tables within Visual Studio. My C# code is connecting to the database using Linq to SQL. The table I am having problems with is not updating on SubmitChanges().
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
tbl_Inventoryv2 inv = new tbl_Inventoryv2();
inv.Title = addTitleTextBox.Text;
inv.Model = addModelTextBox.Text;
inv.Category = addCategoryTextBox.Text;
inv.Quantity = int.Parse(addQuantityTextBox.Text);
inv.Price = decimal.Parse(addPriceTextBox.Text);
inv.Description = addDescriptionTextBox.Text;
db.tbl_Inventoryv2s.InsertOnSubmit(inv);
db.SubmitChanges();
int id = inv.IdInventory;
MessageBox.Show($"Item creation successful. Item number is {id}");
}
My database does have a primary key called IdInventory that is set to increment. Within the program, the correct increments are working as shown in my MessageBox statement above, but it never actually gets saved to the database. I have also checked the properties of the database file in Visual Studio and the path to the database is correct, as well as the Copy to Output Directory is set to Copy if Newer. Most of the questions I have looked up indicate that is usually the problem, but that doesn't look like the case for me. I am new to SQL and interacting with it via Visual Studio/c#, and SQL in general, so any input is greatly appreciated.
I have a program I created in Visual studio. The program is basically a place for everyone to store passwords for company and external accounts. I want to further this application by automatically creating the company accounts when I create a new user. I approached this by using the binding source. I can get the row into the database but it doesn't use the sql supplied auto increment. I will post the code but I am trying to figure out if I went about this the wrong way. I am not 100% familiar with how the connector and classes that visual studio create when you connect the solution to the database. I am not looking for code to help me do this I am looking for explanations and guidance. If responding with code please help me understand by explaining the code.
DataSet.AccountsRow newdomainuserrow = DBDataSet.Accounts.NewAccountsRow();
newdomainuserrow.USer = userIDTextBox.Text.ToString();
newdomainuserrow.UserName = userIDTextBox.Text.ToString();
System.DateTime moment = new DateTime();
newdomainuserrow.Password = moment.Year;
newdomainuserrow.AccountName = "Domain";
drawingNumDBDataSet.Accounts.Rows.Add(newdomainuserrow);
MessageBox.Show("User Saved");
this.Validate();
this.usersBindingSource.EndEdit();
this.accountBindingSource.Endedit();
this.tableAdapterManager.UpdateAll(this.DataSet);
All help is greatly appreciated.
Matt
I found a solution. The id field is not longer an identity autoincrement field. To increment the id field one by one programmatically like I need to I wrote a simply while statement to get all numbers that were not used. This works if there is a deleted row it will insert one where there is one missing. here is the code I used.
Boolean gotnum;
gotnum = false;
int idnum = 1;
while (gotnum != true)
{
DrawingNumDBDataSet.AccountsRow actrw = drawingNumDBDataSet.Accounts.FindById(idnum);
idnum++;
if (actrw==null)
{
gotnum = true;
idnum--;
}
}
I then set the Id field = to idnum. This is probably not the best practice but it is the best I could come up with.
I am having an issue where I am looking at a legacy application that is using SqlXmlCommand objects to get data from the database. There is an .xsd file that has the tables that are being used, and what fields, their relationships etc. The issue that we are having is it works most of the time, but not all. I am wondering if there is a way to check what is actually being run on Sql Server. I don't have the SQL profiler installed so that option is out.
the code looks like:
SqlXmlCommand xcmd = new SqlXmlCommand(DataAccess.OleDbConnectionString);
xcmd.CommandType = SqlXmlCommandType.XPath;
xcmd.SchemaPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"myXsd.xsd"));
xcmd.XslPath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, String.Format(#"myXsl.xsl", ReportType)));
xcmd.CommandText = "id[#PK=$PK]";
SqlXmlParameter p = xcmd.CreateParameter();
p.Name = "#PK";
p.Value = Id;
using (Stream s = xcmd.ExecuteStream()) { ... }
This blows up at the ExectureStream() with the error:
SQLXML: error loading XML result (XML document must have a top level element.)
We believe that there is some data abnormality that is causing the xml to not generate properly, and that is why we want to see what is exactly run.
Cheers
You can try the below two queries, you might need to tweak it a little, but to give you an idea, the first gives you a list of all requests, and the second will give you the detail of the request by its request id (session_id)
SELECT *
FROM sys.dm_exec_requests
DBCC INPUTBUFFER (12345)
Although I would personally rather try and debug the C# app first and view what's being sent over to the server from the VS debugger before bothering with checking what's being run on SQL Server
Also, DBCC INPUTBUFFER might give you something like EXECUTE dbo.MyStoredProc 'params...', to dig deeper, or otherwise a more straightforward query, you can run this
SELECT r.session_id, r.[status], r.command, t.[text]
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) t
Hi I had developed a C# Budget application using SQL Compact and EF4, I created the EF model through the VS2010 Entity Data Model template. It is all working very well. However I am considering developing a iPhone app to support cash transactions and thought it would be better to have the back end DB supported on both platforms. After creating the SQLite DB and creating a new model I have come across a problem when trying to access referenced data via the Navigation properties in my model. I am getting a NullReferenceException when trying to display a property of a referenced table.
When using the following code I get the exception on the last line:
BudgetEntities budget = new BudgetEntities();
var accounts = budget.BankAccounts.ToList();
foreach (BankAccount a in accounts)
{
Console.WriteLine("Name:" + a.Description);
Console.WriteLine("Number:" + a.AccountNumber);
Console.WriteLine("Type:" + a.BankAccountType.AccountType); //Exception occurs here.
}
Strange thing is that the exception doesn't occur in this example. I'm not sure what is going on?
BudgetEntities budget = new BudgetEntities();
var accoutTypes = budget.BankAccountTypes;
var account = new BankAccount();
account.ID = Guid.NewGuid();
account.AccountTypeID = accoutTypes.First(t => t.AccountType.StartsWith("Credit")).ID;
account.BSB = "3434";
account.AccountNumber = "32323";
account.Description = "Test";
account.TrackingAccount = true;
budget.AddObject("BankAccounts", account);
budget.SaveChanges();
var accounts = budget.BankAccounts.ToList();
foreach (BankAccount a in accounts)
{
Console.WriteLine("Name:" + a.Description);
Console.WriteLine("Number:" + a.AccountNumber);
Console.WriteLine("Type:" + a.BankAccountType.AccountType); //Exception doesn't happen.
}
This is only a simple example and I know I could fix it by adding .Include("BankAccountTypes") to the query however I have other queries that are quite complex that are creating object which include properties from referenced object with in the query and I am not quite sure how to get around this issue for them.
EDIT:
After having a break between projects I have come back to this problem and I have finally resolved my problem. it had nothing to do with the code. It was with the data. I had converted a SQL Compact database to SQLite via a dump and load and had the syntax wrong for my Guid column data. I was inserting the Guid as '7cee3e1c-7a2b-462d-8c3d-82dd6ae62fb4' when it should have been x'7cee3e1c7a2b462d8c3d82dd6ae62fb4'
Hopefully the hair I pulled out working through this problem will grow back :)
Thanks everyone for your input.
In second example your code snippet begins with:
var accoutTypes = budget.BankAccountTypes;
This loads all bank account types to your application and you don't need lazy loading anymore (EF will automatically recognize that these entities were already loaded and fix relations with bank accounts).
First check if your account class is dynamic proxy (just check type of a in the debugger). If it is not you made some mistake in the class definition and lazy loading will not work. Next check if lazy loading is enabled on your context instance (budget.ContextOptions.LazyLoadingEnabled property).
Make sure the BankAccountType property is declared virtual in BudgetEntities.
I am having trouble updating an SQL database, the problem is not that it doesn't update at all, but that particular parameters are being updated while the others are not.
here is the code for updating the parameters:
string EditRequest = "UPDATE Requests SET Description = #Desc, BJustif = #Justif, Priority = #Priority, Requested_System = #Requested, Request_Status = #Stat WHERE";
EditRequest += " Req_ID=#ID";
SqlConnection Submit_conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DBConn"].ConnectionString);
SqlCommand Submit_comm = new SqlCommand(EditRequest, Submit_conn);
Submit_comm.Parameters.AddWithValue("#ID", Request.QueryString["reqid"]);
Submit_comm.Parameters.AddWithValue("#Desc", DescBox.Text);
Submit_comm.Parameters.AddWithValue("#Justif", JustifBox.Text);
Submit_comm.Parameters.AddWithValue("#Priority", PriorityList.SelectedValue);
Submit_comm.Parameters.AddWithValue("#Requested", RelatedBox.Text);
Submit_comm.Parameters.AddWithValue("#Stat", 1);
Submit_conn.Open();
Submit_comm.ExecuteNonQuery();
Submit_comm.Dispose();
Submit_comm = null;
Submit_conn.Close();
get_Description();
Page.ClientScript.RegisterStartupScript(this.GetType(), "Refresh", "ReloadPage();", true);
this function is called by a button on a pop-up form which shows the parameters content that is being changed in a text box which is also used to submit the changes back to the database, but when I press submit, the parameters which are displayed on the form don't change, I can't find any problem wit the code, even though I've compared it to similar code which is working fine.
In case you need to, here is one of the text boxes I'm using to display and edit the content:
<asp:TextBox ID="JustifBox" TextMode="MultiLine" runat="server" Width="250" Height="50"></asp:TextBox>
What exactly is wrong with the code?
EDIT: I forgot to mention that when I traced the function, it appeared that the controls' content did not change when I submitted them, but were resubmitted as if they were unchanged in their original form.
You mentioned two problems here:
1) Fields in the database are not updated when the UPDATE is performed
2) The UI is not updated with the latest data
First tackle the SQL UPDATE query. What fields are not being updated? Copy paste the T-SQL query in the query analyzer and then check which field is being updated and which is NOT. Also, your code is OPEN to SQL injections so read about that and then adjust the code.
For the UI not being updated you need to see whether you are even populating the UI fields with the correct object.