Database First with Windows Form - c#

Hi I have a windows Form Application and using Database First Approach. When I am trying to save data using following code its not showing any error but not saving data into my .mdf database.
Models.NorthwoodRetreatsDBEntities db = new Models.NorthwoodRetreatsDBEntities();
db.Treatments.Add(new Models.Treatment() {
Name=_name,
address=_address,
phone=_phoneNo,
Email=_emailAddress
});
db.SaveChanges();
Not showing error I am also trying see is it inserted using the following line of code
bool a = db.ChangeTracker.HasChanges(); //double check if there was any change detected by EF or not?
it is returning true and
int UserID = db.Treatments.Max(item => item.AccommodationID);
Always returning 1 but when I explore database table showing nothing there and also when I am adding second item "int UserID" again 1. Now I am just wondering that can I use Database First EF with Windows Form. Could you please advice.

Related

Linq to SQL not saving to database on SubmitChanges()

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.

DROP command denied to user X for table 'Y'

We are getting ready for a big SQL migration.
Currently, I have the code written, and I am testing it out with data on my local machine.
Step 1 is to throw out the existing data in the table before I import the new stuff:
using (var txn = m_mySqlConnection.BeginTransaction()) {
using (var cmd = new MySqlCommand("TRUNCATE TABLE `blah_blah`;", m_mySqlConnection, txn)) {
cmd.ExecuteNonQuery();
}
// other code
}
But, the TRUNCATE command is throwing an exception whenever I try to execute it with the MySQL user account I am running the code with:
I tried going into MySQL Workbench to give this userid DROP permission, but all I could find was a way to add DROP under the View section.
I tried that, but it did not work.
How do I go about giving this user the ability to remove the data in these tables so that I can test my populate script?
TRUNCATE deletes the table. Try using DELETE FROM Table.

Entity Framework insert doesn't work

I have a very simple windows form project with Entity Framework.
Simply I draged my tables from "Data Source" tab in my "form" and it generate for me a "DataGridView" and a "BindingSource".
Data bound successfully and when I run project I can see "DataGridView" filled with data correctly and I can update any cells value from "DataGridView".
Problem is I can not insert any rows in my "DataGridView".
Here is some codes that I wrote hope it be useful to solve problem:
Teachers_DBEntities context = new Teachers_DBEntities();
private void SaveItem_Click(object sender, EventArgs e)
{
context.SaveChanges();
MessageBox.Show("saved successfully");
}
private void Form1_Load(object sender, EventArgs e)
{
teachers_tableBindingSource.DataSource = context.teachers_table.ToList();
}
Upates for comments
I tested my "BindingSource" and found that it successfully understand if new record insert in "DataGridVeiw", but changes won't apply in database when I call context.savechanges();
context.savechanges() works fine when I update a cell, but it doesn't work when I try to insert a new record in my "DataGridView".
In my edmx file I mapped all columns correctly and primary key StoreGeneretedPattern property is set to Identity and its Entity Key property is set to true. Its auto-increment property in my SQL Server database file is set to true.
any help is appreciated.
context.savechanges() works fine when I update a cell, but it doesn't work when I try to insert a new record in my "DataGridView".
What do you mean by "it doesn't work"? New record does not appear in database? Of course it won't.
In this line
teachers_tableBindingSource.DataSource = context.teachers_table.ToList();
you're breaking DataSource's connection to context. Any new item inserted into it will be inserted not into teachers_table, but into List you created over it.
using (var context = new YourEntities ())
{
var dpt = new yourObject { Name = "Test" };
context.yourObject.Add(dpt);
context.SaveChanges();
}
you are missing to add object in the context
In .Net 4.5 I get this error when I remove ToList():
Data binding to a store query is not supported.
Instead populate a DbSet with data, for example by calling Load on the DbSet, and then bind to local data.
I had exactly this same problem. And after a lot of hours, I just finally found myself the solution...
I'm using C#, .Net Framework, Entity Framework 6.4
If I set
teachers_tableBindingSource.DataSource = context.teachers_table.ToList();
data is updated in DB but not inserted.
If I set (as suggested)
teachers_tableBindingSource.DataSource = context.teachers_table;
I get the error:
System.NotSupportedException HResult=0x80131515 Mensaje = Data
binding directly to a store query (DbSet, DbQuery, DbSqlQuery,
DbRawSqlQuery) is not supported. Instead populate a DbSet with data,
for example by calling Load on the DbSet, and then bind to local data.
For WPF bind to DbSet.Local. For WinForms bind to
DbSet.Local.ToBindingList(). For ASP.NET WebForms you can bind to the
result of calling ToList() on the query or use Model Binding, for more
information see http://go.microsoft.com/fwlink/?LinkId=389592.
Finally I got the answer tnanks to that hint:
context.teachers_table.Load(); //Load records in this DataSet<>
teachers_tableBindingSource.DataSource = context.teachers_table.Local.ToBindigngList();
Now it works. Data is deleted, inserted and updated properly in database.

Entity Framework, SQLite and Lazy loading

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.

error while updating a database in ASP.NET

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.

Categories