I am saving data to the database "successfully", using:
try
{
// Save the new Client now.
Profile profile = new Profile()
{
Salutation = Salutation,
FirstName = FirstName,
MiddleName = MiddleName,
LastName = LastName,
Gender = Gender,
DateOfBirth = DateOfBirth,
CompanyName = ClientCompanyName,
StreetAddress = StreetAddress,
Suburb = Suburb,
PostCode = PostCode,
State = State,
Country = Country,
ABN = ABN.ToString(),
ACN = ACN.ToString(),
TelephoneNumber = TelephoneNumber,
MobileNumber = MobileNumber,
EmailAddress = EmailAddress
};
database.Profiles.Add(profile);
database.SaveChanges();
Console.WriteLine("Client saved.");
}
catch (Exception exception)
{
Console.WriteLine(exception.Message + Environment.NewLine + exception.InnerException);
}
and it says it's been saved. But when I look in the database - nothing's there!
And, when I try to get the first name of the person I just added, it returns the entire SELECT statement - not their first name:
var hisname = database.Profiles.Where(x => x.FirstName == "Jase");
What gives?
This is a C# Windows Console application.
The same code works on my website.
Update
This is what it returns to me when I try to do SELECT:
You didn't show us your connection string yet, and from your question, it's not clear if you see this behavior only when running your app from within Visual Studio or also outside of VS.
If you happen to be using SQL Server Express and the AttachDbFileName=somename.mdf approach, and you observe this behavior when running your app inside Visual Studio, then keep on reading.
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MyDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MyDatabase;Integrated Security=True
and everything else is exactly the same as before...
Related
I wonder why my SQL Server Express database table doesn't get updated when the method below executes successfully?
public void addUser(User user)
{
string query = "INSERT INTO users (username, password, firstname, lastname, isactive, accesslevel) VALUES (#usr, #psw, #fname, #lname, #status, #access)";
pSqlConn = new SqlConnection(pConnectingString);
SqlCommand cmd = new SqlCommand(query, pSqlConn);
SqlParameter pmtrUsername = new SqlParameter("#usr", user.Username);
SqlParameter pmtrPassword = new SqlParameter("#psw", user.Password);
SqlParameter pmtrFirstname = new SqlParameter("#fname", user.Firstname);
SqlParameter pmtrLastname = new SqlParameter("#lname", user.Lastname);
SqlParameter pmtrStatus = new SqlParameter("#status", user.IsActive);
SqlParameter pmtrAccessLevel = new SqlParameter("#access", user.AccessLevel);
cmd.Parameters.Add(pmtrFirstname);
cmd.Parameters.Add(pmtrLastname);
cmd.Parameters.Add(pmtrUsername);
cmd.Parameters.Add(pmtrPassword);
cmd.Parameters.Add(pmtrStatus);
cmd.Parameters.Add(pmtrAccessLevel);
pSqlConn.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Success!");
pSqlConn.Close();
}
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. StoreManagerDB)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=StoreManagerDB;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
Make sure the database connection variable is the right syntax and i advise you include an error syntax to show when the db is not connected
I tried many solutions found on Stackoverflow but none worked. I have a local database linked with EF Designer.
I'm using Entity Framework to create rows and store them into the database. It's working since database.SaveChanges(); returns 1 (not zero). Then I loop on the database rows and I can see that data were well saved.
Nonetheless, when I'm closing my console app and refreshing database, I can't find the values I just added and the rows I generated.
Working on this issue since few hours, browsed Internet but none of the answers helped me.
I already tried to do database.User.Attach() and EntityState.Modified but they didn't work.
I even tried to move my code in a different class, but it didn't work.
public static void AddClient(String firstName, String lastName, int phoneNumber, String email, String wishlist)
{
using (DatabaseEntity database = new DatabaseEntity())
{
database.User.Add(new User() {
First_Name = firstName,
Last_Name = lastName,
Phone_Number = phoneNumber,
Email = email,
Wishlist = wishlist
});
database.SaveChanges();
}
}
I expected data to be saved in the database after closing app, but they aren't.
I found the solution.
When Visual Studio uses local databases, at each debug it copies the databases and works on the copied.
So, I had to add a new connection on the Server Explorer that was targetting my_project_path/bin/debug/database.mdf
Then, I had to edit one of its properties which was Copy to Output Directory. Its new value is now Copy if Newer and now my datas are well saved in the database.
I'm working on a small project in WPF where you can insert, edit and search Recipes. I'm using Entity for this.
Recipe has a property, list<Ingredient>. When I insert an ingredient, it's OK, but when I insert a recipe with a list<Ingredient>, everything is ok except that in table recipe, there is no column ingredient at all. But in debug I clearly can see that in my method where I insert a recipe , the object recipe has ingredients count... I have spend couple hours trying different things out but with no luck.
This is how I insert (same as ingredient , where everything works)
public static void InsertRecipe(Recipe recipe)
{
RecipeDbContext ctx = new RecipeDbContext();
ctx.Recipes.Add(recipe);
ctx.SaveChanges();
}
Screen-shots from debug:
Recipe Table
Recipe object properties
Just for testing purposes , the ingredients should come from a listbox later on.
When I press ctrl property menu is fading away (reason why screen-shot is the way it is)
The whole User Instance and AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. RecipeDataBase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=RecipeDataBase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
First, you must insert Recipe item and get the ID :
public static int InsertRecipe(Recipe recipe)
{
RecipeDbContext ctx = new RecipeDbContext();
ctx.Recipes.Add(recipe);
ctx.SaveChanges();
return recipe.recipeID;
}
And after that you can insert all Ingrédients, Something like that
public static void InsertIngredient(List<Ingredient> Ingredients, int recipeID)
{
IngredientDbContext ctx = new IngredientDbContext();
foreach (var ingredient in Ingredients)
{
Ingredient newItem = new Ingredient { IngredientID = ingredient.Ingredient,..., recipeID = recipeID};
ctx.Ingredient.Add(newItem);
}
ctx.SaveChanges();
}
I'm using Visual Studio 2010 to build an ASP.NET web application, I'm working on dynamically populating (part) of the site map from information in a database. Right now I just have a dummy table in my App_Data folder, called DrugTest.mdf. The table is just called DrugTest1, which only has one field, DrugName. Where I'm hitting a wall is actually getting the data out of that table. Part of what I'm confused about is the connection string. I've looked at a lot of different information about connection strings, most notably http://www.connectionstrings.com/ but I'm a little confused as to how to actually apply said information to this project.
EDIT: I'm using SQL Server 2008 RC.
For example: Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Password and User Id are pretty self-explanatory, but as far as I know I didn't get either one of those, I just added a table to the App_Data folder and filled it with dummy data. ServerAddress is a little confusing, because this information isn't really stored on a server, it's just stored locally. And I'm honestly not sure what Initial Catalog means.
Here's the code to populate the sub-tree. You'll notice the connection string is left blank.
string connString = ""; // get the connection string
string commandString = "SELECT drugName FROM DrugTable1";
SqlConnection connection = new SqlConnection(connString); // connect to db
SqlCommand command = new SqlCommand(commandString, connection); // set up the command
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet drugs = new DataSet();
adapter.Fill(drugs);
foreach (DataRow row in drugs.Tables[0].Rows)
{
string drugName = row["Name"] + "";
SiteMapNode node = new SiteMapNode(this, drugName,
"~/PlaceHolderUrl?path=" + drugName,
drugName);
AddNode(node, root);
}
Furthermore, I've got a nagging suspicion that I'm not going about this the right way. I think this will be the proper implementation once the database is up and running, but for right now I just want to get it working so it's ready to go - just slap in the proper connection string and table/field names.
So, finally, my question(s): How would I go about connecting to this local table? What format should my connection string be? I noticed there's a lot of them. Is there a better way to do this/am I doing this wrong?
Another way of getting the right connection string check this out in the ServerExplorer window
On the Menu click on View->Server Explorer
In the Server Explorer window locate DrugTest.mdf
Right click the file and select Properties
You can see the right connection string in the properties
Copy the connection string and use
Note: that the file location was hard-coded. You might need to use |DataDirectory| later
Try replacing the Initial Catalog portion of your connection string with AttachDbFilename=|DataDirectory|DrugTest.mdf.
Also, if you're using SQL Server Express, you might need to include the instance in the Data Source, so might try Data Source=mySeverAddress\SQLExpress, where SQLExpress is the instance name.
BTW, at the http://www.connectionstrings.com site, you can find this information in the SQL Server 2008 page if you scroll down a bit to the section titled "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance."
I am creating an app for my work to track behavior management over the course of a school year. To do this, I obviously needed a database. I built the program so that it would, when opened, check to see if the database exists, and if it doesn't, it creates one, and inputs the schema. This works perfectly on my dev computer, but when I switch it to a computer using windows XP it gives an error saying system.io.filenotfoundexception. I can't figure out why it won't create the database.
I am using Visual C# 2010 Express. And the database is made in sql server ce.
if (!File.Exists("chart.sdf"))//Checks if file is already in existance when app is opened
{
dbCreated = createDb();//If there is no database, creates one
}
public bool createDb()//Creates the database if needed
{
bool success = true;
//Holds sql schema for the table
string[] tableCreateArr ={"create table childNameId"
+ "(childId INT IDENTITY PRIMARY KEY, "
+ "childFName nchar(40), "
+ "childLName nchar(40));",
"create table leaderNameId"
+ "(leaderId INT IDENTITY PRIMARY KEY, "
+ "leaderFName nchar(40), "
+ "leaderLName nchar(40));",
"create table TagPulledId"
+ "(tagId INT IDENTITY PRIMARY KEY, "
+ "childId INT, "
+ "leaderId INT, "
+ "day TINYINT, "
+ "month TINYINT, "
+ "year INT);",
"CREATE TABLE tagInfo"
+ "(tagId INT, "
+ "color nchar(10), "
+ "description ntext)"};
SqlCeEngine dbCreate = new SqlCeEngine(connectString()); // creates the database obj
dbCreate.CreateDatabase(); // creates the database file
SqlCeConnection tempConnect = new SqlCeConnection(connectString());//Connects to the new database
SqlCeCommand objCmd = new SqlCeCommand();//Creates an sql command obj
tempConnect.Open(); // opens the connection
objCmd.Connection = tempConnect; //Connects the command obj
foreach (string strCmd in tableCreateArr)//Iterates throught he sql schema to create the tables
{
try
{
objCmd.CommandText = strCmd; //sets the CommandText to the next schema entry in the array
objCmd.ExecuteNonQuery(); //Executes the create query
}
catch (SqlCeException sqlError)
{
MessageBox.Show(sqlError.Message, "SQL Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
success = false;
}
}
tempConnect.Close();
return success;
}
I can't figure out why the app isn't making the database, it seems to work on some computers, while not working on others. Any help would be great! Thank you.
if (!File.Exists("chart.sdf"))
You seem to want to create the database in the same directory as your program. Yes, that will work on your dev machine but that's not going to work on a regular machine. The typical install directory (c:\program files\etc) does not permit write access to files.
You will need to use Environment.GetFolderPath() to get an ApplicationData directory that you can write to.
It is often a lot easier and less error prone to let an installer create the appdata directory and copy the initial .sdf file in there. Albeit that Setup projects are not supported by the Express edition. There does come a point where hacking code to work around the Express edition's restrictions is defeating the price of the product license. You're pretty close here.
Make sure you have deployed all the dll Sql Server Compacts need. I'm not sure you get them when you install .NET framework. The dll needed are :
sqlceca35.dll
sqlcecompact35.dll
sqlceer35EN.dll
sqlceme35.dll
sqlceoledb35.dll
sqlceqp35.dll
sqlcese35.dll
You can find more details on this MSDN page about Sql Compact Deployment for various versions of the database engine.