I am currently developing a solution with both an ASP.NET project, and a WPF application. I have a common project too, with an ADO.NET entity model, where entities are generated from a database.
If i try to call anything from my database (MySQL) from my WPF, ASP or a Test project i get a InvalidOperationException where it says that no connection string named "DataModel" could be found in application config file.
I then have to add entity framework connectionstrings and other stuff to each project, in order to be able to fetch data from my common project or database. It also means if i want to change the db connection i have to do it in every single project. Isn't there a smarter way to do this?
Thanks..
Isn't there a smarter way to do this You're doing what most people do, at least for small and medium environments, by putting the connection string in each project.
Most projects need different connection strings for different environments (DEV, QA, PRODUCTION). I use and highly recommend the free add-in Slow Cheetah. That tool allows you to define XSLT transforms to modify XML files in your project. In this case, I use it to drop in the correct connection string depending on the build settings.
When you are ready to create a build for the PRODUCTION environment, you just change the Visual Studio solution configuration to Release, and the generated web.config/app.config contains the PRODUCTION connection string.
You can pass the connectionstring that has to be used to the constructor of your DbContext. You have 3 options to pass a connectionstring:
Pass nothing, EF will look for defaultconnectionstring in configfile, if none is found it will throw an error.
Pass the name of the connectionstring you want to use, if it's not found in the config file EF will use the default connectionstring.
public partial class MyDb : DbContext
{
public MyDb(string connectionStringName) : base(connectionStringName)
}
Pas a connectionstring to the constructor. EF won't look in any config files and just use that one, this is probably what you're looking for:
public partial class MyDb : DbContext
{
public MyDb(string connectionString) : base(connectionString)
//Or hardcode it in:
public MyDb() : base("datasource=...")
}
Edit: It is indeed not good practice to do the above, I'm just saying it's possible.
Related
I'm new to Entity Framework Core as I'm currently migrating over from EF6. We use a database first model.
I've created a .Net Standard class library where I've imported EF Core and have used the scaffolding command in VS to import one of my tables as a test - which worked.
We have a couple of different replica databases that we use for geo-redundancy and reporting purposed, but all have the same model.
I've set up the different connection options, somewhat like point 2 in the answer in this post Using Entity Framework Core migrations for class library project so we can support connections to the different databases.
Now I want to go about adding the rest of the tables in. I have seen mention of Migrations, but that seems to be for code first models.
I then tried to use the "-Force" command on the scaffolding, which did import an additional table, but I lost my multi-database support.
In EF6 I had this logic in the Context.tt file, so when I retrieved updates from the database it would retain the custom connection options I had.
Is there a way to replicate this in EF Core or something I am missing?
Also, for something as simple as a new column on a table, should I still run the same command?
Thanks in advance,
David
* UPDATED *
I ended up using EF Core Power Tools which is a great package and allows complete control over the model, much like the context.tt file used to.
For anyone looking in future, I reverse engineered and used the Handlebars templates in EF Core Power Tools. I pass the 3 connection strings I use in the startup of the application and can then set optional booleans to indicate which connection to use - an enum may be more elegant for anyone starting again but this makes migration easier for us.
In the DbConstructor.hbs, I updated it to:
{{spaces 8}}public {{class}}(bool ReadOnlyDatabase = false, bool ReportsDatabase = false) : base()
{{spaces 8}}{
if (ReadOnlyDatabase)
_connectionString = ReadOnlyContext;
else if (ReportsDatabase)
_connectionString = ReportsContext;
else
_connectionString = ReadWriteContext;
{{spaces 7}} }
The DbContext.hbs file is:
{{> dbimports}}
namespace {{namespace}}
{
public partial class {{class}} : DbContext
{
public static string ReadWriteContext = "";
public static string ReadOnlyContext = "";
public static string ReportsContext = "";
private readonly string _connectionString;
{{{> dbsets}}}
{{#if entity-type-errors}}
{{#each entity-type-errors}}
{{spaces 8}}{{{entity-type-error}}}
{{/each}}
{{/if}}
{{{> dbconstructor}}}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionString);
}
{{{on-model-creating}}}
}
}
Supply a DbContextOptions to the constructor:
public MetadataContext(DbContextOptions<MetadataContext> options)
: base(options)
{
}
Maybe EF Core Power Tools can help you? (I am the author)
You need to post more of your code so we can see what’s going on. At a guess it sounds like you are customizing the generated context class. It will be overwritten with each scaffold operation and as you note the migration support is there to drive db Schema updates from model changes. I.e. it’s for code first.
The db first scaffold approach seems that to be written with the expectation that the scaffold will be done once and thereafter models and contexts will be manually updated.
We have a workflow that involves re scaffolding the DbContext in response to db schema updates and consequently do three things:
scaffold a localhost or SSPI db so the embedded connection string contains no passwords of value.
tolerate the annoying warning in CI/CD about the connection string the scaffolder generates each time that cant be disabled.
we use extension methods to add functionality to the DbContext when necessary so we never need to alter the generated code.
Now I would not suggest extension methods to initialize the different connection strings.
Those I am sure are already coming from config but if not, and you are making a console rather than asp.net core app which makes configuration driven creation of DbContexts really easy I would really suggest learning how to use at least Microsoft.Extensions.Configuration to configure your DbContext instances from an appSettings.
I can’t share a code sample of initializing a DBContext with an DbOptionsBuilder directly because my guilty secret is I always get the DI in Asp.net Core to do it for me.
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.
I have used EF5 for my project and I encrypted my connection string in project's web.config file.
And I replaced the constructor of Entities like this:
public PEntities()
// : base("name=PaypalEntities")
: base(Cryptography.DecryptConnectionString())
{
}
But when I want to update my database model with EF wizard, it asks to me for a new connection string and credentials and replaces my connection string in my config file with this. So my project doesn't run properly.
How can I solve this problem?
I'd strongly encourage you to have the Entity framework model in a separate project. If you do that, the project can have its own connection string that points to your reference database (the one you use for making changes as and when necessary). Thus, the running assembly, whether it be a web project or anything else, will just refer to the model project and can have its own connection string.
Yes...
The Solution is, Create a Partial class with same namespace and write the method into it.
Now whenever you update database or edmx file you will find it's default constructor. just delete it.
refer this
http://forums.asp.net/post/4722699.aspx
Try to uncheck the "Save entity connection settings" checkbox:
I'm working on a WinForm application. I've implemented data-access logic into a "library project" that I set as reference in my WinForm project. I'm using LINQ to SQL to connect to my project database, mapping the tables I use into a dbml file. Now I have to publish my project and change the connection string to point to the production DB.
Is it possible to change the connection string without re-compile the project?
It'll be very useful at debug-time and for maintenance...
I've tried to change it in app.config and also in the Settings file, but it seems to still point to the development DB.
Where am I doing wrong?
The solution suggested in this article is very good: http://goneale.com/2009/03/26/untie-linq-to-sql-connection-string-from-application-settings/
But I decided to solve my issue in a different way.
Without modifying anyting in the dbml file I added in my DAO class a constructor that takes a parameter:
public MyDataAccessClass(string connectionString)
{
_connString = connectionString;
}
then instead of using DataClasses() constructor to instantiate the LINQ-TO-SQL class, I replaced it with DataClasses(_connString).
Now I can use the data access library where I need. The connection string will be set in app.config of the referencig application (or anywhere else).
I am using Entity Framework and recently came to realize the benefits of having your EF model in another project within the same solution so that I can build multiple UIs from it.
I moved it over to a new class library project and updated all the references to the entities in the web project to use the new dll generated by the project. Everything has gone smoothly, except for one small snag. When I moved EF over to the new project, somehow it was still reading its connection string from the web.config in the web project (don't ask me how because I have no clue).
I used "Update Model from Database" in the EF designer and it did not find a connection string (as I expected after moving it over to the new project) so I used the wizard to generate a new connection string, which it did just fine. The new connection string now resides in App.config within the class library project. The connection string in the properties window is correct now, and the designer is reading it from the App.Config. I went ahead and deleted the connection string from Web.Config in the web project.
Now when running the application I get the following error:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
If I paste the connection string back into the Web.Config it all works just fine. I do not want to create a new EF model from scratch because it is a fairly complicated model and I did a lot of restructuring after pulling in from the DB. I have poured over the generated CS file as well as the XML in the edmx file and cannot find anything useful. Any help is much appreciated. Obviously for now, until I figure this out, I'm just leaving the connection string in web.config since, for whatever reason, that seems to work.
This is by design; while the config file in the class library is what the designer will use, the configuration file of the actual application is what will get used at runtime. Whether that's Web.config for an ASP.NET project or App.config for a Winforms or WPF project, it's the application configuration file (or something higher up, like Machine.config) that will be used; the file in the class library is not part of the application.
If you're trying to provide an EF model that will work without having to specify the connection string in the application or web configuration file, then you'll have to store the connection string some other way (you could always hard-code it) and pass it into the appropriate overload of your context's constructor.
My solution is generally to provide a static parameterless function on the context itself that calls this overload with the appropriate connection string.