VS is storing my data in some other database? - c#

Visual studio creates a new database out of thin air to store my data. This is my DbContext:
public class LinkedDataContext : DbContext
{
public DbSet<LinkedData> LinkedData { get; set; }
}
No errors are being thrown, I just end up with another database that is only visible through the SQL Server Object Explorer unlike my initially created database which is the top one in the screenshot.
Edit
I migrated the whole accounts database generated by the MVC project to the MSSQL 2014 server. I simply added a database there and changed the connection string, then it automaticaly populated the database with the needed tables.
So I created my custom table, exactly as it was in the local database. I removed the local databases, the other connection strings and the Controller. Then I rebuild my project and created the controller again. But VS/MVC/EF or whomever is responsible is still creating a local database for my custom data.
When I create the controller it seems to find my table in MSSQL SERVER 2014, otherwise I would get a safe dialogue to store the sql file locally. So what is really happening here? Like I said, the account functionality worked instantly like a charm. My custom table in MSSQL simply won't get used.
EDIT
So I set the DefaultConnectionFactory in Web.config to my MSSQL SERVER 2014 and now it is generating a new Database inside my MSSQL SERVER. It seems to be the namespace, when I create a controller I need to pass in the namespace for the both the Model class and Context class.
Model class: LinkedData (DataVisualization.Models)
Data context class: LinkedDataContext (DataVisualization.Models)
The databases that keep getting generated automatically to hold my custom data are called: DataVisualization.Model.LinkedDataContext.
Does anyone have any idea what is really going on here?

I believe it is just the connection string in your Web.config. When you create a DbContext from an existing database outside of your project, Visual Studio prompts
The connection you selected uses a local data file that is not in the
current project. Would you like to copy the file to your project and
modify the connection?
If you select Yes, this copies the database file into your project, sets its Build Action to Content, sets a relative reference to it in your connection string and sets it to copy to your output directory on build.
If you modify the connectionString in your Web.config to point to the correct database you should be set (for future reference, answer No when asked if you want to copy it, unless that is really what you want to do - e.g. for a database file you're distributing with your binaries).
As an example, see the two connections listed below. You would see something like ProjectContext if you selected Yes, or something like ExternalContext if you selected No.
<connectionStrings>
<add name="ProjectContext" connectionString="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=|DataDirectory|\Database.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
<add name="ExternalContext" connectionString="data source=(LocalDB)\MSSQLLocalDB;attachdbfilename=C:\Programming\.Net\DataVisualization\Data\DataVisualization\App_Data\Database.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
Note that the actual syntax of the connectionString may be different in your app depending on settings used, but the key part is the |DataDirectory| reference vs the correct path. The path is what you'd need to modify.

The shorthand solution is this:
public class LinkedDataContext : DbContext
{
public DbSet<LinkedData> LinkedData { get; set; }
public LinkedDataContext() : base("DefaultConnection")
{
}
}
I was assuming it would take the default connection if there was no connection named after the context. The reason was that I did not get a error so the connections would have been fine. Yet without specifying a connectionString in web.config it just seem to take part of the default string, since it does find my database and throws in it's namespace and creates a new database out of thin air. I might be new to MVC but I find this ridiculous default behavior. So I still have no clue what the idea behind this is.
Unless you want to have a couple of hundred connection strings for a fairly sized application the only way to go seems to be to call the parent constructor and specify the DefaultConnection there. Kind of ironic you have to "specify" default behavior.
Unlike what #tomtom told me, in almost 10 hours I did not find a single scenario that resembles mine. Maybe I was not clear but in my initial post I did specify each step I took. Using a MSSQL SERVER does not seem to be necessary.
Hope this helps someone else out.

STANDARD BEHAVIOR. As bad as it is. Your db template is copied to the runtime every time you hit the "debug" button, so you always start with a new datababase. Painfull as hell. Not sure how other's solve this - I never use this side of visual studio, I have a sql server installed and create my databases there manually. Makes sure i am always working against a defined copy. Obviously VS has no rights to create databases there ;)
If you bother using google or the site search a little you find tons of similar questions - this is a standard problem people regularly get trapped in because it is totally not what they expect.
(if you ask me, the whole db maintenance side of EF is broken anyway, including the "migrations" that hardly can use SQL Server most basic features).

Related

EF6 Queries Using Wrong Database

I am using Devart dotConnect for MySQL with Entity Framework 6 in a Windows Forms application (.Net Framework 4.8). I'm using the DB first approach with a dynamic connection string. My application can connect to any number of databases all with the same schema, so I am building the connection string based on input from the user. I have used this approach on several other projects and have never encountered this issue before. I have spent the last day searching for someone reporting a similar issue, with no luck.
I've created my EDMX model using an empty database (meaning no data, but full schema) called entity_model. I can create instances of the DBContext-derived entity class, and I can even use the attached database to perform general queries on the attached server (e.g. get a list of installed database). I can even perform SQL queries into the database identified in the connection string (using DbContext.Database.SQLQuery), and the results are what I expect. However, when I try to use the DbSet-derived members of the Entity class, my queries are always being directed at the database that I used to generate the model, regardless of the database identified in the connection string.
Stepping through the code, I can see that the settings in the entity object all look correct (entity.Database.Connection.ConnectionString looks exactly like I would expect, and entity.Database.Connection.Database has the correct database name). However, if I examine the internal query value (DbSet.SQL) for any of the DbSet objects, I get something similar to this:
SELECT
Extent1.ID,
Extent1.Field1,
Extent1.Field2,
Extent1.Field3,
FROM entity_model.table1 AS Extent1
where entity_model is the database that I used to create the model. I've done enough testing to know that the queries are actually being executed against this incorrect database, rather than the one passed in through the connection string.
As I've said, I've used this same technique on other projects and have not run into this issue. I've even stepped through some old code and I can see that the contents of the DbSet.SQL field contains no reference to any database (neither the one used to create the model, nor the one from the connection string). This is what I would expect to see in my new project as well.
Can someone explain to me how EF decides whether to include the schema name in the DbSet.SQL field? This is making me a little crazy.
I've tried this across a number of the 50 or so databases that I have installed on my machine, so I know the problem is not with any particular database.
I've found a solution (actually 2 solutions) to this problem. The basic problem is that EF is using the schema specified in the edmx EntitySet element by default:
<EntitySet Name="table1" EntityType="Self.table1" Schema="entity_model" store:Type="Tables" />
This behavior can be turned off in 2 ways. Either add the following lines to your applications startup code:
using Devart.Data.MySql.Entity.Configuration;
...
var config = MySqlEntityProviderConfig.Instance;
config.Workarounds.IgnoreSchemaName = true;
Or add the following sections to your config file:
inside the configSections element:
<section name="Devart.Data.MySql.Entity" type="Devart.Data.MySql.Entity.Configuration.MySqlEntityProviderConfigurationSection, Devart.Data.MySql.Entity.EF6, Version=8.21.2066.0, Culture=neutral, PublicKeyToken=09af7300eec23701"/>
And then after the configSections element:
<Devart.Data.MySql.Entity xmlns="http://devart.com/schemas/Devart.Data.MySql.Entity/1.0">
<Workarounds IgnoreSchemaName="true"/>
</Devart.Data.MySql.Entity>
I found a third option online, and that was to simply delete the schema name from each of the EntitySet elements in the edmx file, but I think that could cause some issues if you ever try to update the model from a database.
I'm hopeful that this answer will prove useful to someone else down the road.

ASP.NET Core MVC local database and model controller

I have created an ASP.NET Core web application using the MVC pattern (by following this tutorial) and connected it to a local database that is now populated with some data. I have two questions, if someone please help me understand and answer them:
1) My default connection string is set to the following:
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-MyAppName;Trusted_Connection=True;MultipleActiveResultSets=true"
}
Is it possible, only by changing the name and path in this connection string, to re-create the exact same database elsewhere with the data that is currently stored in it (for example, as backup)?
I have found the local database here:
C:\Users\my-name\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances\MSSQLLocalDB
But when I try to copy the .mdf file to back up the database, I get an error that says the file is open and cannot be copied. What is it open in? How can I simply back the db file up?
2) After creating a custom controller, I noticed that all the provided properties of my Personmodel are used in the auto-generated code; e.g. in my case:
public async Task<IActionResult> Create([Bind("Birthday,ID,Username,EmailAddress")] PersonModel personModel)
I thought this would mean that if we change the code in the model class, we need to search for and effect the changes accordingly, but then I realized if I want to keep using auto-generated code, I have to do all the same steps as when I am generating it for the first time, and then when it asks if I want to replace the old code with new code, I choose yes.
Is there a better way of doing this, because this would overwrite my custom code every time and destroy the data stored in my local database. Particularly, when I store data in its local database, and then I decide to change a column name or add something, this would override everything...
How do I go about this situation?
Question 1
The .mdf and other files associated with the database will be in use by the SQL Server service. If you want to take a backup, use SQL Server Management Studio - right-click the database in the object explorer, select Tasks and then Backup. If you want to use the backup database then you need to restore it - again in the object explorer, right-click the "Databases" folder and select Restore Database and then browse to wherever you created the backup file.
Question 2 (updated 7th Sep)
When you change your model classes, you can use the add-migration command in the console to generate a new migration class containing the code to transform the database from its current structure to the new structure which matches the updated models. If the migration can cause data loss, then backup the database and restore the backup under a different name before running update-database, You can then create a script to transform the data from the backup into the new structure of the updated database.
Scaffolded components are a bit different to Entity Framework migrations. Migrations are truly auto-generated classes, and most of the time you wouldn't need to update (or even look at) the generated code. Think of scaffolded components as being more like a kind of template - it's a way of getting started with the classes, methods, markup etc that you're most likely to need, which is quicker than writing it all from scratch. It's not an alternative to writing code though, the intent is that once you've created the scaffolded code, you'll maintain it manually going forward. There is no way (that I know of) to automatically update scaffolded code to match a new model whilst retaining any edits you've made to it. You have two options
Re-scaffold the code and then apply your edits to it
Update the code manually to match the new model
All you can really do is weigh up the two options and decide which one is the least effort.

Entity Framework on .mdf file

I am working on some project at the moment and I have to use local database. So, I created a new service-based database (no tables atm). Then I wanted to add Entity Framework support.
Because I never used Entity Framework before, I was referring to that link: http://msdn.microsoft.com/en-us/data/jj200620.aspx.
Everything is OK, but here it gets complicated. I created my DataContext class with DbSet inside it. But, when I run my unit test, table is created on Localdb (not inside my .mdf file).
What to do?
I am pretty sure, that I did choose which database to use correctly (actually did that 3 times already), but still, data tables are created on LocalDb. What I am doing wrong here?
I am complete beginner with that (been only using doctrine ORM). Otherwise I can insert data and all, it is just on the wrong database.
When your doing code first development in EF, you can force EF to only ever consider one connection string name.
One of the constructors (of which there are quite a few overloads) on the EF Data Context parent classes, takes a simple string.
This string is given to be the name of a connection string in the App or Web config to use.
You make the call something like this:
using System.Data.Entity;
namespace MSSQL_EFCF.Classes
{
public class DataAccess : DbContext
{
public DataAccess() : base("myConnectionString")
{}
public DbSet<MyTableObject> MyObjects { get; set; }
}
}
You can still put any code you need for your own start-up (Such as DB Initializer calls) inside your constructor, and all that will get called once the base call completes.
The advantage of doing things this way forces entity framework to always use the named connection string and never anything else.
The reason this catches many developers out, and why it runs off an uses localdb is deceptively simple.
The Entity Framework DbContext by default will use the name of the data context derived class as a database name, and if it can't find a suitable connection string in any config file by that name, makes the assumption that your working in development mode without a full backing data store.
In my example above, EF would examine App and/or Web.config for a connection string called "myConnectionString"
Once it makes this development decision, it knows that localdb will be present as this gets installed with the latest builds of visual studio, and so it will automatically seek out a connection and populate it with a db that follows the name of the context in which it's used.
I've previously written a blog post on the subject, which you can find here :
http://www.codeguru.com/columns/dotnet/entity-framework-code-first-simplicity.htm
NOTE: The above applies to any database that you connect with using EF, it's the connection string that decides what/where the actual data store is.

Change configuration file when using Linq to SQL

I've read a few links but most are in relation to when deploying or i've missed a trick in the middle so dont fully understand hence asking the below question......
I have a live, test and local environment (all have their own individual connection strings). I create a solution with 2 projects (for example) 1 is a ASP .Net website and other is a Class Library. Within the class library i add a Linq to SQL and add a connection to it. The connection string is stored in an app.config file.
What i would like to do is be able to switch between the environments so the connection string is updated to reflect the environment i am using without having to manually type in the connection string. I've seen this done but not sure how to do it myself? Im using VS2010. Could anyone advise or point me in the right direction?
Thanks
You could potentially use #if DEBUG and have two connections strings in your app.config - one called Test one called Live - I would suspect that debugging would indicate that you are in the test environment and on release you would be live.
Please refer to this link http://msdn.microsoft.com/en-us/library/4y6tbswk.aspx
Another option is to simply have an input at some point to indicate which environment the application is running on - you could do this with a checkbox or radio button or even through appSettings in app.config by specifying ConnectionMode and setting it to 1 or 2 if the setting reads 1, then use the test connection string, if it reads 2 Live connection string.

Entity Framework 4.1 Code First Freeze

I'm having trouble getting EF 4.1 working on my computer. It seems to be some problem with my database settings. I was trying out this simple walkthrough:
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-code-first-walkthrough.aspx
But when it reaches db.Categories.Add(food); it just freeze.
I have a normal SQL Server 2008 R2 installed, not SQL Express. There also seems to be some problems with creating .mdf files instead of a direct connection to the localhost SQL server.
I've also tried adding an entity model with a database connection, but this does not seem to work. Do anyone have any pointers for me.
Thanks for any answers :)
edit:
I now get a System.Data.ProviderIncompatibleException with "Vendor returned no ProviderMaifestToken-string"
I guess this is because Database Re-Initialization.
If your EF code try to drop and create database with SQL Management Studion open or connected.
This situation comes up.
I found the problem. These tutorials do not contain information about some vital adjustments that I needed to make it work.
1) Your application must have an App.config containing a connectionstring named with the same name as your class that inherited from DbContext. In my case "TestEF_CF.ProductContext".
2) The database cannot be created before you start to use it. Just set the Initial Catalogue to the name you want Entity Framework to create when it autocreate the database.
Once I did this, it worked properly. I got further with the first step, but got an exception when I tried to save to the database. When EF autocreated the database everything worked fine.
One thing that may have made it more problematic on my development environment could be the fact that I cannot use local mdf files directly. Still it would not hurt if the EF team could share these details more open than they do now, it would save me (or us) some frustration.
Try setting the datasource on the connection string to .\SQLEXPRESS
It did work for me

Categories

Resources