I am using VS2010 , and I am building a simple wpf application using C#
I have built a database using SQL Server 2008
in my application I created a LINQ to SQL class and created a dbml file
then I created a datacontect and did everything right
BUT
when I can't aaccess my database file everytime I try to , I mean when I insert anew row in my datacontexct I can check it and see it but when I look in my mdf file I can't find anything
I think that my datacontexct must be connected to my database file somehow
please help me because I seriously need it
The connection string, that is passed to the datacontext, references the MDF.
// Northwnd inherits from System.Data.Linq.DataContext.
Northwnd nw = new Northwnd(#"northwnd.mdf");
var cityNameQuery =
from cust in nw.Customers
where cust.City.Contains("London")
select cust;
foreach (var customer in cityNameQuery)
{
if (customer.City == "London")
{
customer.City = "London - Metro";
}
}
// you must call this this commit the changes
nw.SubmitChanges();
Call .SubmitChanges() on your DataContext after adding an item.
Related
My Code :
var dbpath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "ot.db3");
Context myContext = null;
try
{
var dbcon = new SQLiteConnection(dbpath);
var db= dbcon.Query<records>("SELECT * FROM records WHERE sno = ? ", "1");
int count = db.Count;
}
catch (IOException ex)
{
var reason = string.Format("The database failed to create - reason {0}", ex.Message);
Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}
I Create a Sqlite Database from my SQL Server Database.
Now I save it to my Phone on this path (Android/Data/Application/File)
Now using Sqlite-net-pcl nugget package for Sqlite Connection the connection works fine showing have no error.
When I try to read a table from database this Give any error that "No Such Table exist in database". And the table exists in the database and is populated with data.
What can I do?
Thanks in advance
Why are you writing the SQL query? You could make it more simple, something like, conn.Get(id);
You will only need to add [PrimaryKey] to your PK in the model.
Also, I suggest you to not use SQLite.SQLiteConnection and use SQLiteAsyncConnection instead, so you will be able to get data using "await conn.GetAsync(id)" and this way it won't block the main thread.
Create a Blank Database – A database reference can be created by passing the file path the SQLiteConnection class constructor. You do not need to check if the file already exists – it will automatically be created if required, otherwise the existing database file will be opened.
var db = new SQLiteConnection (dbPath);
Save Data – Once you have created a SQLiteConnection object, database commands are executed by calling its methods, such as CreateTable and Insert like this:
db.CreateTable<Stock> ();
db.Insert (newStock); // after creating the newStock object
Retrieve Data – To retrieve an object (or a list of objects) use the following syntax:
var stock = db.Get<Stock>(5); // primary key id of 5
var stockList = db.Table<Stock>();
For more info use following link:
https://developer.xamarin.com/guides/android/application_fundamentals/data/part_3_using_sqlite_orm/#Using_SQLite.NET
You need to check in your DB file if the table really exists.
Extract the database from your Android device/simulator with ADB
Example: adb pull //.db .
It will download the DB file to your computer.
Then, use a tool such as "DB Browser for SQLite" (http://sqlitebrowser.org/) to open your DB file and check if your table exists.
Other common mistakes when using SQLite with Android are:
the file is not found (the path in your connectionstring is not good)
the name is not the one your think (maybe in your case, it is "Record" and not "Records")
Hope it will help.
I'm adding new lines to a database for our company's "order list" for each order created, using the firebird ado.net client. The code i've written works fine for listing items, but inserting new ones doesn't appear elsewhere (e.g. in flamerobin). What I think is happening is that the transaction isn't being committed, seeing as it's recognised within my code (can't add duplicate values).
Code:
using (FbConnection fbCon = new FbConnection)
{
fbCon.Open();
***command w/ parameterised command string***
using (FbTransaction fbTrans = fbCon.BeginTransaction())
using FbCommand orderCommand = new FbCommand(cmdString, fbCon, fbTrans)
{
***Adding parameters and values***
try
{
int recordsAffected = orderCommand.ExecuteNonQuery();
fbTrans.Commit();
}
catch (FbException E)
{
fbTrans.Rollback();
fbCon.Close();
throw E
}
}
recordsAffected returns 1 but I am not able to see the updated values in flamerobin or the db management program. Am i missing something?
If anyone else runs into this problem, it's in Visual Studio's debugging settings. https://visualstudiomagazine.com/blogs/tool-tracker/2012/05/dealing-with-local-databases-or-why-your-updates-dont-stick.aspx explains pretty clearly, but basically VS makes a copy of your database in bin/Debug of your project (Ostensibly to not mess with your data) but if you actually need to use/view the data externally, either link your external application to the debug database (e.g. flamerobin). You may also need to set your project database settings to Copy if Newer if you want your updates to stay, as the default setting copies the database into the folder each time you run your c# app.
Here is everything that I did:
In a visual studio 2013 C# project, I created a service database (.mdf file). Note: I changed the name from Database1.mdf to fghLocalDB.mdf.
I opened this database in the server explorer.
I created 2 tables called Country and CarbonDioxide using the table designer.
I added an entry to the Country table as shown by the Data Table of the Country table.
I did the following to create a DataSet my application can use. I created a Data Source by clicking on the "Project" option on the top menu bar and clicking on the "Add New Data Source ..." option from the drop down.
This is what my project files looked like at this point.
I wrote the following code in the main method thinking that this would be all I need to write to the database.
// Create a connection to the DataSet and TableAdapters that will communicate with our
// local database to handle CRUD operations.
fghLocalDBDataSet dataSet = new fghLocalDBDataSet();
fghLocalDBDataSetTableAdapters.CountryTableAdapter countryTableAdapter =
new fghLocalDBDataSetTableAdapters.CountryTableAdapter();
try
{
// Insert a row into Country table. EDIT 1 Will comment after first program run.
Console.WriteLine(countryTableAdapter.Insert("United States"));
// Actually writeback information to the database?
// dataSet.AcceptChanges(); EDIT 2 commented this as LeY suggested it was not needed.
// EDIT 3 Validation code as suggested by Ley.
var dt = new fghLocalDBDataSet.CountryDataTable();
var adapter = new fghLocalDBDataSetTableAdapters.CountryTableAdapter();
adapter.Fill(dt);
foreach (var row in dt)
{
// This does not get executed after a second run of the program.
// Nothing is printed to the screen.
Console.WriteLine("Id:" + row.Id + "----Name: " + row.Name);
}
Console.Read();
}
catch(SqlException exception){
Console.WriteLine("ERROR: " + exception.ToString());
}
Console.ReadLine();
I ran the program and everything seemed fine.
I opened the tables by right clicking on these tables in the server explorer and pressing "Show Data Table".
The "United States" row was not added as wanted.
I think it has to do with the connectionstring. I right clicked on my project and opened properties.
Here I made sure the connection string matched that of the local database by looking at the string in the properties of the database. They are the same.
I copied and pasted the actual text for each connection string:
Connection string of project:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fghLocalDB.mdf;Integrated Security=True
Connection string of actual database (.mdf file):
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;Integrated Security=True
I am assuming |DataDirectory| is equal to C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf; since in the picture above when I clicked on the button to expand the Value of the connection string the connection properties window opened up and had this path for the database file name.
My question in a nutshell is does instantiating a DataSet object in the code automatically create a connection to a SQL service-based database for CRUD operations?
If not how do I connect my DataSet object to my sql database so that way I can actually write to the database when using the TableAdapters?
I read the following links:
Insert method of TableAdapter not working?
TableAdapter Insert not persisting data
Use connectionstring from web.config in source code file
Do I need an actual SqlConnection object? and how to I connect this to the DataSet & TableAdapters?
I never used tableadpter.insert() method. But I tried it on my local machine, and it works.
I can't figure out your problem based on the information you provided, sorry, but I can point you a direction.
If you created everything from wizard, you don't need to worry about the connection, the table Adapters will handle the connection for you. The connection string (you circled) will be added to your app.config file as well as your setting class automaticly. That is how your application (or you) uses it.
var countryTableAdapter = new CountryTableAdapter();
countryTableAdapter.Insert("United States");
This 2 lines of code are enough to insert the row into database if there is no exception thrown, I don't know why it doesn't work for you. Maybe the way you verify it somehow goes wrong, but you can verify it in another way.
The countryTableAdapter.Insert method will return the number of row get affected, in your case , should be one. So put the following code in , and set a breakpoint after it. if the rowAffected == 1, then the insertion works.
var rowAffected = countryTableAdapter.Insert("Test2")
If you need more confirmation , try this.
var dt = new fghLocalDBDataSet.CountryDataTable();
var adapter = new CountryTableAdapter();
adapter.fill(dt);
foreach (var row in dt){
Console.WriteLine("Id:" + row.Id + "----Name: " + row.Name);
}
Console.Read();
you will see all the records in your table.
I hope this will help.
By the way, from your code
dataSet.AcceptChanges();
The line of code above doesn't update the database at all. It only modify your local data storage.
it overwrites your dataRow original version using current version and change the current version row state to unchanged.
Only the tableadapters can talk to database (not true I know, but I just want to make a point that Dataset can not talk to database directly).
And I usually only need tableadapte.Update method and pass the dataSet or dataTable in with correct RowState.
The tableAdapter.update method will call AcceptChanges on each row eventually if it successfully updated the database.
You should never need to call AcceptChanges explicitly unless you only want update your dataset in memory.
I recommend you to read ADO.NET Architecture to get the big picture how DataSet and TableAdapter worked.
It was my connection string after all. In my original post, I said I had two connection strings:
Connection string in project settings:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\fghLocalDB.mdf;Integrated Security=True
Actual connection string in fghLocalDB.mdf file:
Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;Integrated Security=True
Something went wrong with
|DataDirectory| = C:\Users\gabriel\Source\Workspaces\Capstone\Sandbox\aduclos\QueryDataMarketConsole\QueryDataMarketConsole\fghLocalDB.mdf;
in my App.config.
My Solution:
What I did was copy the actual connection string of the .mdf file from the .mdf properties panel and paste it into the project properties => Settings => Value field of the connection string set up.
Afterwards I ran my code again and sure enough the data persisted in the tables.
I did not need dataSet.AcceptChanges(); as #LeY pointed out. I also did not need a TableAdapter.Update(dataset) call as posted in other solutions. I just needed the TableAdapter.Insert("...") call.
EDIT: ALSO Most importantly to answer my original question, instantiation a DataSet does not create a connection with the local database. Instead instantiating a TableAdapter does establish a connection with the database!
I am trying to run a .NET project someone gave me that contains a database MDF file and uses LINQ queries in the C# code, such as:
db = new DataClasses1DataContext();
using (db)
{
res01 r = new res01();
r.comb_bars = 1;
r.end_dte = b_list.Last().dteTme.Date;
r.pers = pers;
r.st_dte = b_list.First().dteTme.Date;
r.sym = sym;
db.res01s.InsertOnSubmit(r);
db.SubmitChanges();
}
I see that this code runs when I debug it, but it doesn't seem like any rows were added to the database. Yet, I didn't get any errors while running the code. I am using Visual C# Express 2010. How can I see what has been added in the database MDF file that is part of the project?
Data is stored in the database file inside bin/Debug folder. Open that and check.
See this for more details on connecting to compact db
try to rebind() the grid. because the data have to be reloaded.
Okay, this is really weird. I made a simple database with a single table, Customer, which has a single column, Name. From the database I auto-generated an ADO.NET Entity Data Model, and I'm trying to add a new Customer to it like so:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
class Program
{
static void Main()
{
Database1Entities db = new Database1Entities();
Customer c = new Customer();
c.Name = "Harry";
db.AddToCustomer(c);
db.SaveChanges();
}
}
}
But it doesn't persist Customer "Harry" to the database! I've been scratching my head for a while now wondering why such a simple operation doesn't work. What on earth could be the problem!?
EF requires that you have a unique index for many operations.
Try adding an identity field (primary key) to your table. Delete and recreate your model and try again.
Edit:
It looks like you are running this from a console app.
Do you have a connection string in the app.config file?
Do you have more than one project in your solution?
Are you getting any exceptions?
Edit2:
Next things to try:
Use SQL Server profiler to see what is being sent to the database
Open the EF model in an editor to see the xml, check if there are any errors
Place db in a using statement to ensure the connection/transaction is closed cleanly before process exit.
OK, here's a longshot. Are you sure your connection string is pointing to the right place? And the connection is functioning?
You can verify it by using SQL Server Management Studio to add some records to your test database, and then do something like
foreach (Customer c in db.Customers)
{
Console.WriteLine(c.Name);
}
Make sure that the "Copy to Output Directory" property of the database file is not set to "Copy always." If it is, every time you rebuild the application, the database may be clobbered with a pristine copy.
See: Entity Framework not flushing data to the database