An attempt to attach an autonamed database for file failed - c#

The compiler is giving me this error:
An attempt to attach an auto-named database for file failed. A database with the same name exists or specified file cannot be open, or it is located on UNC share.
I've been reading around other stackoverflow posts and they mention it might be a connectionstring problem, but I'm coding this in linq, not ado.net code. I don't use a traditional connectionstring. In fact, I had to use a namespace to call the tableAdapter in order for me to access the data source I needed.
The code being used is as follows:
using CustomerInvoices.MMABooksDataSetTableAdapters;
namespace CustomerInvoices
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MMABooksDataSet mmaBooksDataSet = new MMABooksDataSet();
InvoicesTableAdapter invoicesTableAdapter = new InvoicesTableAdapter();
CustomersTableAdapter customersTableAdapter =
new CustomersTableAdapter();
private void Form1_Load(object sender, EventArgs e)
{
invoicesTableAdapter.Fill(mmaBooksDataSet.Invoices);
customersTableAdapter.Fill(mmaBooksDataSet.Customers);
var invoices = from invoice in mmaBooksDataSet.Invoices
join customer in mmaBooksDataSet.Customers
on invoice.CustomerID equals customer.CustomerID
orderby customer.Name, invoice.InvoiceTotal descending
select new
{
customer.Name,
invoice.InvoiceID,
invoice.InvoiceDate,
invoice.InvoiceTotal
};
string customerName = "";
int i = 0;
foreach (var invoice in invoices)
{
if (invoice.Name != customerName)
{
lvInvoices.Items.Add(invoice.Name);
customerName = invoice.Name;
}
else
{
lvInvoices.Items.Add("");
}
lvInvoices.Items[i].SubItems.Add(invoice.InvoiceTotal.ToString());
lvInvoices.Items[i].SubItems.Add(Convert.ToDateTime
(invoice.InvoiceDate).ToShortDateString());
lvInvoices.Items[i].SubItems.Add
(invoice.InvoiceTotal.ToString("c"));
i += 1;
}
}
}
}

I figured it out. Thru the data source, I went into the connection property window and found the connection path file, I changed it to the correct one
Data Source=localhost\sqlexpress;Initial Catalog=MMABooks;Integrated Security=True
And it Worked. It seems the error is because the connectionString was pointing to the wrong path file. Hope this helps others. Thank you.

Related

C# Entity Framework + SQLite - selecting database file by user.

I made WPF app which uses Entity Framework and SQLite. At the beggining I loaded my database via ADO.NET Entity Data Model. Everything was working quite good but now I want to add option for users to choose from local files with database (all tables in databases should be the same but data could be diffrent for diffrent files). So to test this solution I copied my database file and made some changes in code:
I edited DbContext file by adding: (I found this here https://stackoverflow.com/a/23105811)
public appDBEntities(string filename)
: base(new SQLiteConnection() { ConnectionString =
new SQLiteConnectionStringBuilder()
{ DataSource = filename, ForeignKeys = true }
.ConnectionString }, true)
{
}
The users is selecting database file by using this function:
private void testButton_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".db";
dlg.Filter = "Database files (*.db)|*.db";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name
if (result == true)
{
// Open document
publicVariables.databasePath = dlg.FileName;
}
}
Than i want to test if everything is ok by displaying some data from database with this function:
public static void showParticipants(DataGrid participantsDataGrid, string connectionString)
{
using (var db = new appDBEntities(connectionString))
{
var query = from c in db.Participant
join gender in db.Sex on c.Sex equals gender.id
join club in db.Club on c.Club equals club.id
join nation in db.Nation on c.Nationality equals nation.id
select c.id;
var data = query.ToList();
participantsDataGrid.ItemsSource = data;
db.Dispose();
}
}
Like this:
showParticipants(testDataGrid, publicVariables.databasePath);
But this function
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
Is throwing this exception:
The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development. This will not work correctly. To fix this problem do not remove the line of code that throws this exception. If you wish to use Database First or Model First, then make sure that the Entity Framework connection string is included in the app.config or web.config of the start-up project. If you are creating your own DbConnection, then make sure that it is an EntityConnection and not some other type of DbConnection, and that you pass it to one of the base DbContext constructors that take a DbConnection. To learn more about Code First, Database First, and Model First see the Entity Framework documentation >here:http://go.microsoft.com/fwlink/?LinkId=394715
I have a similar task working by changing config entry, maybe it would work for you:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["DbStatisticsEntities"].ConnectionString =
"metadata=res://*/Models.DbStatisticsModel.csdl|res://*/Models.DbStatisticsModel.ssdl|res://*/Models.DbStatisticsModel.msl;provider=System.Data.SQLite.EF6;provider connection string='data source=" + this.DBFileName + "'";
connectionStringsSection.ConnectionStrings["DbStatisticsEntities"].ProviderName = "System.Data.EntityClient";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
Properties.Settings.Default.Save();
Properties.Settings.Default.Reload();

Check if table exist using SQLite-PCL in a UWP

I'm stuck with how to check if a table already exists.
I have been searching but like many times before I can't find good examples.
The ones I find on SQLite don't work with the PCL version. I can't understand why though, so if anyone has a good site where to go please feel free to add them.
These are the ones I have used:
http://blogs.u2u.be/diederik/post/2015/09/08/Using-SQLite-on-the-Universal-Windows-Platform.aspx
https://code.msdn.microsoft.com/windowsapps/Implement-SQLite-Local-8b13a307#content
This is my code showing how I have tried to check it, but it only checks the path, which always exists. Not a smart solution when I thought about it.
private void LikeItButton_Click(object sender, RoutedEventArgs e)
{
var sqlpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Filmdb.sqlite");
using (SQLite.Net.SQLiteConnection conn =
new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), sqlpath))
{
if (File.Exists(sqlpath))
{
AdMovieID();
}
else
{
conn.CreateTable<MovieID>();
AdMovieID();
}
}
}
You could execute a query:
SELECT name FROM sqlite_master WHERE type='table' AND name='MovieId';
by doing
var tableExistsQuery = "SELECT name FROM sqlite_master WHERE type='table' AND name='MovieId';"
var result = conn.ExecuteScalar<string>(tableExistsQuery);

Insert new row with SQLite PCL

I am making a movieApp in UWP and i want to store a id from a movie if the user likes the movie. I have tried with txt but hade much problem with the access denied error. So i decided to use sqlite insteed.
I used this to get starded:
https://code.msdn.microsoft.com/windowsapps/Implement-SQLite-Local-8b13a307#content
I have been searching for a while now and all info i find dosent work with sqlite pcl.. it looks like many off the methods dosent exist that the examples i find uses.
So it seems there is little examples out there.. mabey you guys could push me in the right way..
This is my code so far for this:
private void LikeIt()
{
var sqlpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Filmdb.sqlite");
using (SQLite.Net.SQLiteConnection conn =
new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), sqlpath))
{
if (File.Exists(sqlpath))
{
AdMovieID();
}
else
{
conn.CreateTable<MovieID>();
AdMovieID();
}
}
}
private void AdMovieID()
{
var sqlpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Filmdb.sqlite");
SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), sqlpath);
//This is where i have tried some of the things i have found
// like this:
//SQLite.Net.SQLiteCommand insertSQL =
//new SQLite.Net.SQLiteCommand("INSERT INTO MovieID(ID) VALUES(?), conn)<-- error: dosent work no constructor that takes arguments;
//insertSQL.Parameters.Add(MovieID.ID);
//Just to test if something is saved
var allaId = conn.Find<MovieID>(sqlpath).ID;//<-- just tried this and it dosent work either "Object reference not set to an instance of an object."
foreach (var id in allaId)
{
Test.Text = id.ToString();
}
}
The class that i use with SQLite:
public class MovieID
{
public string ID { get; set; }
}
You're not inserting a new item anywhere in your code, from what I can see.
Check out this simple code example:
using (var connection = new SQLiteConnection(path))
{
connection.CreateTable<MovieID>();
connection.Insert(new MovieID { ID = "someId" });
var movies = connection.Table<MovieID>().ToList();
}
If you inspect movies in the end it should have one item inside, a MovieId object with "someId" ID.

How to change db connection programmatically c# Entity Framework

I've built my project and named the db connection "VMaxEntities"
The connection string exists in web.config.
I have another connection string "Development_VMaxEntities"
Whenever I call the db, I use the code using (VMaxEntities db = new VMaxEntities())
This calls:
public partial class VMaxEntities : DbContext
{
public VMaxEntities()
: base("name=VMaxEntities")
{
}
What I want to do is connect to a development database instead of the live one, IF the current URI contains localhost.
So - thanks to cgotberg's answer below, here's what I used to get it working: (note, I add the password here instead of in web.config)
public VMaxEntities()
: base("name=Secure_VMaxEntities")
{
if (System.Web.HttpContext.Current.Request.Url.Host == "localhost")
{
var connectionString = this.Database.Connection.ConnectionString + ";password=***********";
this.Database.Connection.ConnectionString = connectionString.Replace("catalog=VMax", "catalog=DEV_VMax");
}
else
{
this.Database.Connection.ConnectionString += ";password=************";
}
}
I've done something like this in the past
using(var db = new VMaxEntities())
{
var connectionString = context.Database.Connection.ConnectionString;
var datasource = context.Database.Connection.DataSource;
var databaseServer = "yourDevDatabaseServerName"
db.Database.Connection.ConnectionString = connectionString.Replace(datasource, databaseServer);
}

Which data is data.ToList() in Product.cs referring to for the AdventureWorks project?

I I have a project - AdventureWorks and a file - Product.cs that contain the code:
public static List<ProductCategory> GetCategories()
{
var db = new AdventureWorksEntities();
var data = from o in db.ProductCategories orderby o.Name select o;
return data.ToList();
}
The exception EntityException was unhandled by user code was thrown when it hit the following line of code
return data.ToList();
So, I use try and catch to catch the exception and use Console.WriteLine to see what is the exception, it will give me
A first chance exception of type 'System.Data.EntityException' occurred in System.Data.Entity.dll
and the list box will be empty.
Inside the Default.aspx.cs file, it contain:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<ProductCategory> data = DataAccessLayer.Products.GetCategories();
lbCategories.DataSource = data;
lbCategories.DataBind();
}
else
{
if (lbCategories.SelectedIndex != -1)
{
string category = lbCategories.SelectedValue;
Response.Redirect("/Products.aspx?id=" + category);
}
}
}
It seems that it will retrieve some form of data / information from the DataAccessLayer.
The following is an extract from the Web.config file:
<connectionStrings>
<add name="AdventureWorksEntities" connectionString="metadata=res://*/mdlAdventureWorks.csdl|res://*/mdlAdventureWorks.ssdl|res://*/mdlAdventureWorks.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\sqlexpress;Initial Catalog=AdventureWorksLT2008R2;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
The following shows part of the project structure:
+ DataAccessLayer
- Products.cs
+ Styles
- Site.css
+ Default.aspx
- Default.aspx.cs
- Default.aspx.designer.cs
+ mdlAdventureWorks.edmx
- mdlAdventureWorks.Designer.cs
I am suspecting that it might got to do with the mdlAdventureWorks.edmx file but I don't know how can I further troubleshoot and diagnosis the problem since the project was not written by me.
Appreciate any advises given.
Try this to see if you are actually getting anything back from your database:
public static List<ProductCategory> GetCategories()
{
var db = new AdventureWorksEntities();
try
{
if (!db.ProductCategories.Any())
{
Console.WriteLine("Nothing in DB for ProductCategories");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
var data = from o in db.ProductCategories orderby o.Name select o;
return data.ToList();
}

Categories