So I have been using Entity Framework for some time (on v5 for my main project). One question I have always had, but could never find a definitive answer to - does the name of my connection string have to match the name of my DbContext in order for EF to work correctly?
It appears so (and I have never done anything differently), but I would prefer not to have to provide a "magic string" in my Web.config in order for EF to work. It would be better, in my opinion, to keep DefaultConnection as the name and EF connects up some other way.
Here is the references from my Web.config (some names changed):
<connectionStrings>
<add name="MyContext" connectionString="Data Source=|DataDirectory|MyDatabase.sdf" providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>
...and...farther down...
<entityFramework>
<contexts>
<context type="MyProject.Path.To.MyContext, MyProject.Path.To, Version=1.0.0.0, Culture=neutral">
<databaseInitializer type="MyProject.Path.To.MyInitializer, MyProject" />
</context>
</contexts>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
Any insight would be appreciated.
One question I have always had, but could never find a definitive
answer to - does the name of my connection string have to match the
name of my DbContext in order for EF to work correctly?
No. You can pass a connection string name into the base constructor for DbContext, i.e.
public class MyDbContext : DbContext
{
public MyDbContext()
: base("MyConnectionStringName")
{
}
}
There's also a constructor on DbContext that takes a DbConnection argument if you prefer to create the connection yourself.
Finally, you can provide your own implementation of IDbConnectionFactory and use it instead of the default LocalDbConnectionFactory one specified in the app.config. You change it in the config or you set it at runtime as follows:
Database.DefaultConnectionFactory = new MyCustomConnectionFactory();
Related
I am developing a WPF application that uses Entity Framework v.6 with the approach Code First to build and manage a local database which is created on the client computer itself.
When I install the application on a client computer and launch it, I receive the following error when the context tries to create the database:
Expansion of |DataDirectory| failed while processing the connection string. Ensure that |DataDirectory| is set to a valid fully-qualified path.
In app.config I have set the following configuration of Entity Framework:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb"/>
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
</entityFramework>
My context class contains the following code:
class EntityContext : DbContext
{
public DbSet<Car> Cars { get; set; }
public DbSet<Trip> Trips { get; set; }
public DbSet<Volunteer> Volunteers { get; set; }
public DbSet<Motivation> Motivations { get; set; }
public DbSet<PaymentType> PaymentTypes { get; set; }
public EntityContext() : base("StaccoDataBase")
{
System.Data.Entity.Database.SetInitializer(new CreateDatabaseIfNotExists<EntityContext>());
}
}
I have tried to fix the problem setting the |DataDirectory| in the App.xaml.cs as follows:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.SetData("DataDirectory", Directories.DBDirectory);
}
But the issue still persists.
I would really appreciate if someone can help me.
Just a wild guess - what if you used this connection string:
Data Source=(LocalDb)\\MSSQLLocalDB; AttachDBFilename=|DataDirectory|StaccoDataBase.mdf; integrated security=SSPI
First of all, use the |DataDirectory| directly in your connection string (don't "inject" it via that string.Format() call), and secondly, add the .mdf extension to the database file you want to attach.
Also, I'd store this connection string in the app.config - don't create it at runtime, because the constructor call here:
public EntityContext() : base("StaccoDataBase")
will try to find StaccoDataBase as a connection string name in your config file.
So use this:
app.config:
<configuration>
.....
<connectionStrings>
<add name="StaccoDataBase"
connectionString="Data Source=(LocalDb)\\MSSQLLocalDB;AttachDBFilename=|DataDirectory|StaccoDataBase.mdf; integrated security=SSPI"
providerName="System.Data.SqlClient" />
<connectionStrings>
.....
</configuration>
In a very simple Silverlight Application I have a DomainService Class which has a single method that returns a list of Letter Objects.
The application works fine when I run it in VisualStudio. However, when I publish it to a folder on my Windows 10 local machine and run it using IIS (version 10.0.166299.5) I get the following error:
The remote server returned an error: NotFound.
at System.ServiceModel.DomainServices.Client.OperationBase.Complete(Exception error) at System.ServiceModel.DomainServices.Client.LoadOperation.Complete(Exception error) at System.ServiceModel.DomainServices.Client.DomainContext.CompleteLoad(IAsyncResult asyncResult) at System.ServiceModel.DomainServices.Client.DomainContext.<>c__DisplayClass1b.b__17(Object )
I supect this is due to something being wrong in missing in my WebConfig file. My WebConfig Currently looks like this:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.6" />
<httpRuntime targetFramework="4.6" />
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<add name="DomainServiceModule" preCondition="managedHandler" type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>
The code for my Domain Service Class is like this:
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.Server;
using SilverData.Web.Models;
namespace SilverData.Web.Services
{
[EnableClientAccess]
public class DrugsRiaService : DomainService
{
public IQueryable<Letter> GetAllLetters()
{
List<Letter> letters = new List<Letter>();
Letter letterA = new Letter { ID = 1, Statement = "Mike" };
Letter LetterB = new Letter { ID = 2, Statement = "Emma" };
Letter LetterC = new Letter { ID = 3, Statement = "Peter" };
letters.Add(letterA);
letters.Add(LetterB);
letters.Add(LetterC);
return letters.AsQueryable();
}
}
}
The error was due to the problem that .svc file wasn't being served.. The problem got solved with the kind help from the Kyle Abraham on Experts Exchange.
https://www.experts-exchange.com/questions/29084691/RIA-Service-Error-in-a-Silverlight-Application.html
The solution was to add the following line to the webserver section of the Webconfig
<handlers>
<add name=".svc" verb="*" path="*.svc" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</handlers>
I'm not sure, its a guess as I have not used RIA for awhile, but I think letters needs to returned as something other than queryable... try ToList() which causes the query to execute, and the payload is complete with the complete enumeration that was retrieved from the database. Remember, this is a remote call from a client, not a local one that can extend the queryable.
I am using the following connection string within the <configuration> node. But somehow, it seems that it is not saving. Every time I use
System.Configuration.ConfigurationManager.ConnectionStrings["myDB"].ConnectionString
it has a null value, and when I check the index "0" it points to .\SQLEXPRESS.
<connectionStrings>
<clear/>
<add name="myDB"
providerName="System.Data.SqlClient"
connectionString="Server=Server\Instance;Database=anydb;User Id=***; Password=***;" />
</connectionStrings>
The projects is an ASP.NET MVC 2 project.
I really need this to work, since I am learning the code-first Entity Framework. Is there any suggestions?
Things to trouble-shoot on this :
Ensure that EF is configured to use your connection string. You can do this in you DbContext class by passing the connection string name into the base constructor :
public class YourContext : DbContext
{
public YourContext()
: base("myDB")
{
}
}
Ensure that the connection string is the correct web.config (ie in the main root not in Views)
Check that the connection string is not being overridden in the web.debug.config (or web.release.config) if it is being
I developing an mvc web app with Entity Frame]work. I've enabled database migration so that i can add some seed data on each update.
More specifically, i want to add two users and two roles; so the configuration file looks like this:
var roles = (SimpleRoleProvider)Roles.Provider;
var membership = (SimpleMembershipProvider)Membership.Provider;
//// create two roles
if (!roles.RoleExists("Admin"))
{
roles.CreateRole("Admin");
}
if (!roles.RoleExists("User"))
{
roles.CreateRole("User");
}
However there seems to be a problem during the casting; it throws an exception
Unable to cast object of type 'System.Web.Security.SqlRoleProvider' to type 'WebMatrix.WebData.SimpleRoleProvider'.
I suspect that this might be a configuration issue, but i'm not really sure. Does anyone stumbled across the same problem?
That's because SqlRoleProvider does not inherit SimpleRoleProvider. However, you can try using SimpleRoleProvider Constructor (RoleProvider):
var roles = new SimpleRoleProvider(Roles.Provider);
I sorted this out. The problem apparently was related to web configuration. I added the following lines to the web.config file:
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
to explicitly set the role provider. So now the Roles.Provider returns an instance of WebMatrix.WebData.SimpleRoleProvider; thus i don't need to cast any more
I solved this by placing below code in web.config between
<roleManager enabled="true" defaultProvider="simple">
<providers>
<clear />
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="simple">
<providers>
<clear />
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
I am trying to use the ADMembershipProvider to connect to a local ADAM server and I am getting the error in the title. If I remove the enable password reset and the properties it relies on I am able to connect.
I have tried to google it and nothing has come up. Below is my provider config. Any advice would be highly appreciated.
<providers>
<add name="AspNetActiveDirectoryMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADService"
connectionUsername="[username]"
connectionPassword="[password]"
connectionProtection="Secure"
enableSearchMethods="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/"
description="Default AD connection"
requiresUniqueEmail="true"
clientSearchTimeout="30"
serverSearchTimeout="30"
attributeMapPasswordQuestion="department"
attributeMapPasswordAnswer="division"
attributeMapFailedPasswordAnswerCount="badPwdCount"
attributeMapFailedPasswordAnswerTime="badPasswordTime"
attributeMapFailedPasswordAnswerLockoutTime="lockoutTime"
attributeMapEmail = "mail"
attributeMapUsername = "userPrincipalName"
maxInvalidPasswordAttempts = "5"
passwordAttemptWindow = "10"
passwordAnswerAttemptLockoutDuration = "30"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"/>
</providers>
FYI... The closest thing to a similar result was someone who got this error on a similar attribute and he just restarted the machine. That didn't work for me. I did find this article as well http://blogs.msdn.com/b/dansellers/archive/2005/10/20/483272.aspx but I am struggling to get the LDAP admin to make this change. Especially since we already have those properties.
I finally had the LDAP admin perform the steps in the following link an we are up and running.
http://blogs.msdn.com/b/dansellers/archive/2005/10/20/483272.aspx