Updating Local Database with Entity Framework - c#

I have a problem regarding updating local database with Entity framework.
I'll show you just small basic example of a problem, and I will type it literally, so anyone who reads this can see if I forgot something.
In a newely created WPF project, I added New Item -> Local Database,
and then Dataset -> Finish and in that database I'v created a table with 2 columns: ID and name.
Then Add -> New Item -> ADO.NET Entity Data Model for that base
I have made a button with a click event which should add a new values in table columns, but
nothing happends in the database. This is the code I have written:
private void button1_Click(object sender, RoutedEventArgs e)
{
Database1Entities DbTest = new Database1Entities();
Table1 table = new Table1
{
Name = "John"
};
DbTest.AddToTable1(table);
DbTest.SaveChanges();
}
When I execute program, in debug I have the following error:
An error occurred while updating the entries. See the inner exception for details.
I don't understand what's wrong, because when I do the same thing with Database created in SQL server, and connecting to VS2010 via EDM, everything works perfectly.

Related

Dynamic SQL issue - C# Forms (Datagridview)

I am currently trying to update my DataGridView to my database. I want to be able to update it with the enter key. But I am getting this error:
"Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information."
Here is a picture of the code(as well its below in code snippet)
Some of the code
Here is how the Datagridview is loaded:
private void RampBoardLoader()
{
SqlConnection connection = new SqlConnection(ConnectionLoader.ConnectionString("Threshold"));
connection.Open();
SqlCommand selectRampBoard = new SqlCommand("Select_Ramp_Data", connection);
selectRampBoard.CommandType = CommandType.StoredProcedure;
selectRampBoard.Parameters.AddWithValue("#DateID", dateTimeRamp.Value.Date);
dt = new DataTable();
dataAdapter = new SqlDataAdapter(selectRampBoard);
dset = new DataSet();
dataAdapter.Fill(dset, "Ramp_Board");
dgvRampBoard.DataSource = dset.Tables[0];
connection.Close();
}
Here is where I'm trying to update the datagridview:
private void dgvRampBoard_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
scb = new SqlCommandBuilder(dataAdapter);
dgvRampBoard.EndEdit();
this.dataAdapter.Update(dset, "Ramp_Board");
}
}
I've been looking around to try to find the answer to this. Every post I see everyone says that you need to make sure your table has a primary key. My table does have a primary key. It has 2 primary keys. "Flight Number" and "DateID". I'm not sure if it's because I have 2 primary keys, if that's why I'm getting this issue.
Attached is image of Database of my stored procedure. You can also see the columns, I have 2 primary keys
Stored Procedure
How to make life easy:
(Note; this only works in a net framework project; the designer has bugs in net core and Microsoft have disabled it. There are tricks you can pull if you want to work in core, but they basically entail using a net framework project to do the editing and a netcore to do the running)
add a dataset type file to your project
open it, right click its surface, choose add tableadapter
Set up your connection
Choose to use stored procedures to get your data
Choose your sprocs (I assume you have one for updating ?)
Name the Fill/GetData methods appropriately (FillByDateId ?)
Save the dataset
Go to a new form
Open DataSources window on View menu, other windows
Drag the node representing your table, onto your form. You should see a grid, binding source, dataset and navigator appear
That's it, you should be able to just run the app now, enter some date Id in the box, hit fill, change the data, hit save..
You can find the code the designer write for you in the normal code behind and in the FormXx.Designer.cs files if you're curious how it works. A tableadaptermanager will call tableadapter.Update(datatable) on "parent, child" order for every table that needs updating. Table adapter's Update uses the InsertCommand, UpdateCommand and DeleteCommand as appropriate to persist each row change according to what the row state is

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.

Database First with Windows Form

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.

TableAdapter.Update(dataset) not saving to database in Ado.NET

I have seen the other posts on this subject. Yet so far there has been no solution. I am working with Visual Studio 2013 in C#.
I have a database "Database1.mdf" with one table called Customers, which just has two records. I created the DataSet named CustomersDataSet (Menu: Project, Add New Data Source...) based upon this database.
This is my code.
CustomersDataSetTableAdapters.CustomersTableAdapter cta = new CustomersDataSetTableAdapters.CustomersTableAdapter();
CustomersDataSet ds = new CustomersDataSet();
// Fill our customersDataSetTable with the data from customers adapter
cta.Fill(ds.Customers);
Console.WriteLine("BEFORE");
foreach (CustomersDataSet.CustomersRow customer in ds.Customers.Rows)
{
Console.WriteLine(customer.FirstName + " " + customer.LastName);
}
Console.WriteLine("\nMaking changes now...");
// Insert a new record
CustomersDataSet.CustomersRow newCustomer = ds.Customers.NewCustomersRow();
newCustomer.FirstName = "Brian";
newCustomer.LastName = "Faley";
newCustomer.City = "Denver";
newCustomer.State = "CO";
ds.Customers.AddCustomersRow(newCustomer);
// Update a record, [0] = gets access to the first row of the customers table
ds.Customers[0].FirstName = "Robert";
// Delete a record
ds.Customers[1].Delete();
// Update the dataset ds. Commit changes to the database
cta.Update(ds);
Console.WriteLine("\nAFTER");
foreach (CustomersDataSet.CustomersRow customer in ds.Customers.Rows)
{
Console.WriteLine(customer.FirstName + " " + customer.LastName);
}
It works insofar as I do see the changes made to the dataset after "AFTER".
Yet I can run it as often as I wish - never are the changes written to the underlying database. The Update should do just that, but it does not. There is no AcceptChanges() in my code. I have followed up on all these suggestions - they do not lead anywhere.
Would someone have an idea?
I googled far and wide and all posts on this issue are unsolved.
When you debug the application the mdf file is copied to the bin\debug folder and your changes are committed to the database there.
Every time you start the project the mdf in the debug folder gets overwritten with the original database.
You can stop this behavior by going to the database settings in your solution and set the database to copy only if your version is newer.
Chances are your code was working all along.
Hope this helps.

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.

Categories