C# WPF Database Exercise How to update database column - c#

Doing a learning exercise.
Trying to update the database date column for all entries to a new specific value or go through each entry and change date to a new specific value.
I tried using DataContext & Linq but it keeps telling me missing reference which its not so I have reverted to this.
var results = webDataSet.GreyList;
foreach (var elements in results)
{
elements.Date = 55;
}
webDataSet.AcceptChanges();
greyWebTableAdapter.Update(webDataSet.GreyList);
Even If i put Update in a try catch it says it is successful but it will never update the database.
Plus I'd like to thank the people who have nothing to say yet down vote my questions, its people like you who really bring the community together.

To anyone else who took advice to add .AcceptChanges(); by using this it sets the dataSets modified row value from true to false; so when you update the method looks for modified true row's however they are all false so nothing gets updated. Also the other factor to not seeing the database change is because Visual studio 2015 creates a copy of the database from your local folder and duplicates it in your bin folder, so looking for changes in your local folders database is a waste of time.

Related

Remove list values based on series of other values

I have a situation wherein a List object is built off of values pulled from a MSSQL database. However, this particular table is mysteriously getting an errant record or two tossed in. Removing the records cause trouble even though they have no referential links to any other tables, and will still get recreated without any known user actions taken. This causes some trouble as it puts unwanted values on display that add a little bit of confusion. The specific issue is that this is a platform that allows users to run a search for quotes, and the filtering allows for sales rep selection. The select/dropdown field is showing these errant values, and they need to be removed.
Given that deleting the offending table rows does not provide a desirable result, I was thinking that maybe the best course of action was to modify the code where the List object is created and either filter the values out or remove them after the object is populated. I'd like to do this in a clean, scalible fashion by providing some kind of appendable data object where I could just add in a new string value if something else cropped up as opposed to doing something clunky that adds new code to find the value and remove it each time.
My thought was to create a string array, and somehow loop through that to remove bad List values, but I wasn't entirely certain that was the best way to approach this, and I could not for the life of me think of a clean approach for this. I would think that the best way would be to add a filter within the Find arguments, but I don't know how to add in an array or list that way. Otherwise I figured to loop through the values either before or after the sorting of the List and remove any matches that way, but I wasn't sure that was the best choice of actions.
I have attached the current code, and would appreciate any suggestions.
int licenseeID = Helper.GetLicenseeIdByLicenseeShortName(Membership.ApplicationName);
List<User> listUsers;
if (Roles.IsUserInRole("Admin"))
{
//get all users
listUsers = User.Find(x => x.LicenseeID == licenseeID).ToList();
}
else
{
//get only the current user
listUsers = User.Find(x => (x.LicenseeID == licenseeID && x.EmailAddress == Membership.GetUser().Email)).ToList();
}
listUsers.Sort((x, y) => string.Compare(x.FirstName, y.FirstName));
-- EDIT --
I neglected to mention that I did not develop this, I merely inherited its maintenance after the original developer(s) disappeared, and my coworker who was assigned to it left the company. I'm not really really skilled at handling ASP.NET sites. Many object sources are hidden and unavailable for edit, I assume due to them being defined in a DLL somewhere. So, for any of these objects that are sourced from database tables, altering the tables will not help, since I would not be able to get the new data anyway.
However, I did try to do the following to filter out the undersirable data:
List<String> exclude = new List<String>(new String[] { "value1" , "value2" });
listUsers = User.Find(x => x.LicenseeID == licenseeID && !exclude.Contains(x.FirstName)).ToList();
Unfortunately it only resulted in an error being displayed to the page.
-- EDIT #2 --
I got the server setup to accept a new event viewer source so I could write info to the Application log to see what was happening. Looks like this installation of ASP.NET does not accept "Contains" as an action on a List object. An error gets kicked out stating that the method is not available.
I will probably add a bit to the table and flag Errant rows and then skip them when I query the table, something like
&& !ErrantData
Other way, that requires a bit more upkeep but doesn't require db change, would be to keep a text file that gets periodically updated and you read it and remove users from list based on it.
The bigger issue is unknown rows creeping in your database. Changing user credentials and adding creation timestamps may help you narrow down the search scope.

DataGridView: cannot add row or insert to table

I have a DataGridView. It uses a BindingSource, a DataTable in a DataSet, and a TableAdapter to add/change/delete data in a table. It worked OK, but stopped working when I added a field/column, and I can't figure out what I did or how fix it.
The user can add a new row at the bottom of the DataGridView, but when he goes to save, the row disappears and is not saved. In addition, if he tries to type a second new row, the first new row disappears.
Existing Rows can be changed and saved back to the database successfully.
I've been asked for code. OK, here is code. (I've eliminated some error checking done by scanning dtDep) The point that after the third line is executed, there are no rows in dtDep even though a new row had been entered into the DataGridView. If a row had been retrieved, it would be in dtDep and the database table updated by the last statement.
this.Validate();
bsBelkDep.EndEdit();
DataTable dtDep = dsBelk.Tables["belk_elig_dep"];
int n = belk_elig_depTableAdapter.Update(this.dsBelk.belk_elig_dep);
It was a problem with the DataGridView, but I don't know what. I started deleting and re-creating the various object, and after the I recreated the DataGridView, it worked OK. Which was a pain because I have to do significant reformatting, but at least it works.
This is a very old question and I have no way of knowing if it was the OP's original problem, but I had the exact same scenario and this is how I resolved it.
For background: I have a WinForms application built using datasets and an Access database. I migrated that to use Sqlite and anything but datasets. To avoid destroying the application completely, first I copied the strongly typed data tables out, tweaked them to account for changes in the schema and then used PetaPoco to perform the data operations. That worked fine for a single test conversion.
The trouble arose when I wanted to move on and convert all data tables - I wasn't happy manually writing the logic for converting to and from typed data rows and POCOs, so I fell back to writing old school T4 templates to generate typed DataTable, DataRow classes and the necessary remapping code.
Worked a treat - for editing or removing data. But new rows disappeared on "creation", the binding navigator count didn't increment, and of course, when saving, I didn't detect any rows with the RowState of DataRowState.Added. The grid at start up was subtly different - a blank value in all columns instead of a negative number in the ID column. In hindsight, that should have been a big clue.
On reverting the behaviour back to the manually extracted typed class the grid started working again so it was clearly an error in the new code.
End of background; tldr;
The cause of the issue, in my case, was that the my Id column didn't have the AutoIncrement property set. As soon as I configured that to be true (along with setting AutoIncrementSeed and AutoIncrementStep to -1, although neither are required) new rows started being correctly added to the table.

ASP.NET MVC3 database manipulation

Right now, I have a simple web application that displays the entries of a database. One of the fields that is visible in the database is a bool?, which is true, false, or neither. Everything in the database originally should have the bool? set to neither.
Here's what I want to get working: when a user edits an entry in the table by selecting either true or false for the bool? field, I want to be able to run some C# code (that I have already written) and have that entry deleted from the database. This means that the next time that the database is loaded, once again all the entries will have neither true nor false selected in the bool? field.
Does someone know how I can do this simply? (I know very little about querying databases or creating web apps in general.)
My problem was less about how to delete the items and more about how to pick out from the database those chosen to be deleted.
I found that this does the trick:
var toBeRemoved = from m in db.Issues
where m.Remove.HasValue && m.Remove
select m;
I believe when you say "true, false, or neither", the neither means null in the database, so, without seeing your code, I believe you could change the SELECT that retrieves the rows for the view to display, to have a WHERE *field* IS NULL in it. If this doesn't help, please post us some control, view, and model code.

How to Insert a copy of a row (with a new identity) using LINQ to SQL?

I have a number of tables that together make up a "Test" that somebody can take. There are multiple types (scripts) of Test a person can take. I'm working on an Edit function that will allow somebody to edit the Test Questions. I want these edited questions to show up on all new Tests of that type, but still show the old questions when viewing past test scores.
To do this each "Test" has a TestId auto-increment identity (along with its name). When a test is edited I want to make a copy of the test with a new TestId and present the questions for editing.
So what is the best way to make the copy and insert it into my table using LINQ to SQL? This:
DataContext db = new DataContext(ConnectionString);
//Copy old test into identical new test but with a different script ID
var oldScript = db.TestScripts.Single(ds => ds.TestScriptId == oldScriptID);
var newScript = oldScript;
db.TestScripts.InsertOnSubmit(newScript);
db.SubmitChanges();
of course tells me that I Cannot add an entity that already exists.
Is the only way to do this to go through every column in the TestScript and copy it manually, then insert it, and the database will give it a new Id?
Edit
I've also tried
DataContext db = new DataContext(ConnectionString);
//Copy old test into identical new test but with a different script ID
var oldScript = db.TestScripts.Single(ds => ds.TestScriptId == oldScriptID);
var newScript = new TestScript();
db.TestScripts.InsertOnSubmit(newScript);
db.SubmitChanges();
hoping that it would make a new empty row, then I could newScript = oldScript and submit the changes, but it gives me SqlDateTime overflow errors.
Is the cloning part overhere what you are looking for?
http://damieng.com/blog/2009/04/12/linq-to-sql-tips-and-tricks-2
Warning: Ugly hacky untested possibility
How about setting the id to null?
newScript.TestScriptId = null
db.TestScripts.InsertOnSubmit(newScript);
Well I see two ways for you:
Just make a "make copy" function that copies all the attributes over
Use reflection to automaticly copy all properties with the [column] attribute over (Thats a little bit hardcore, and can be alittle magical, if you get it to work)
There are some "magic" functions floating around the web, that saids that they can do it, but I would prefer number 1, and have full control myself.
Also: Ask yourself it it's really the right DB schema you are using, the you need to copy an entire tree, if a person makes a change - maybe a DB change, can make this way easier for you?

System.Data.Linq.ChangeConflictException: Row not found or changed

I wasted the better part of the day on this and am no closer to a understanding the issue than what I was this morning.
I am looping through a set of objects and marking them for deletion. The 2nd one always causes the above exception. tb_invoice has a FK to tb_shipment.
As always, I am probably missing something very obvious, but I have stripped out so much from this code already that there is nothing left, and I am still getting this exception. This is a local SQL 2008 instance and there is of course nothing and nobody changing the invoice in between reading them and calling SubmitChanges(). Help!
myDataContext db = new myDataContext();
IQueryable<invoiceDetail> pendingInvoices
= db.GetInvoiceDetailPending();
foreach (invoiceDetail id in pendingInvoices) {
tb_shipment s = db.GetShipmentById((Guid)id.shipment_id);
db.tb_invoices.DeleteOnSubmit(
db.GetInvoiceById(s.tb_invoices.FirstOrDefault().id)); }
SubmitChanges(); // fails for the 2nd invoice
}
System.Data.Linq.ChangeConflictException: Row not found or changed
Setting the Delete action for the foreign keys in SQL Server to "Cascade" did the same. I wish I had remembered earlier that I ran into this before.

Categories