Ok, this may not be related to EF. I am trying to use the code-first feature and following is what I wrote:-
var modelBuilder = new ModelBuilder();
var model = modelBuilder.CreateModel();
using (AddressBook context = new AddressBook(model))
{
var contact = new Contact
{
ContactID = 10000,
FirstName = "Brian",
LastName = "Lara",
ModifiedDate = DateTime.Now,
AddDate = DateTime.Now,
Title = "Mr."
};
context.contacts.Add(contact);
int result = context.SaveChanges();
Console.WriteLine("Result :- "+ result.ToString());
}
The context class:-
public class AddressBook : DbContext
{
public AddressBook()
{ }
public AddressBook(DbModel AddressBook)
: base(AddressBook)
{
}
public DbSet<Contact> contacts { get; set; }
public DbSet<Address> 开发者_C百科Addresses { get; set; }
}
and the connection string:-
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="AddressBook" connectionString="Data Source=MyMachine;Initial Catalog=AddressBook;Integrated Security=True;MultipleActiveResultSets=True;providerName=System.Data.SqlClient"/>
</connectionStrings>
</configuration>
So, the database name is "AddressBook" and the error happens when I initialize the AddressBook object. I see people suggesting to add (providerName="System.Data.SqlClient") to the connection string. But It does not work in my case. Am I missing anything here?
You should add the System.Data.SqlClient as the value to a new attribute named "ProviderName". Just like below :-
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="AddressBook" providerName="System.Data.SqlClient" connectionString="Data Source=MyMachine;Initial Catalog=AddressBook;Integrated Security=True;MultipleActiveResultSets=True;"/>
</connectionStrings>
</configuration>
I had the same error when I uploaded my website to the production server. My connection string had the providerName
property set. The cuase of the problem was a connection string in machine.config
named LocalSqlServer
and a role provider that has used that connection string:
<roleManager>
<providers>
<add name="AspNetSqlRoleProvider" connectionStringName="LocalSqlServer" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
....
So all I had to do was clearing connection strings and role providers before registering mine:
<connectionStrings>
<clear/>
<add name="DbEntities" connectionString="..." providerName="System.Data.SqlClient" />
</connectionStrings>
...
<roleManager defaultProvider="DefaultRoleProvider" enabled="true">
<providers>
<clear/>
<add name="DefaultRoleProvider" ... />
</providers>
</roleManager>
精彩评论