SimpleMembershipProvider not adding tables to my database - asp.net

I have a standard ASP.NET MVC4 application, and I am building out the DAL with EF Code First. Currently there are around 20-30 models and I am at a point where I want to integrate users and roles. I have research this a ton and still can't seem to get it to work. Here is what I have right now:
In my database initilization class (Gets called every time I change the model) I seed it with a bunch of data, then call this:
public class DbInit : DropCreateDatabaseIfModelChanges<TrackerContext>
{
protected override void Seed(TrackerContext context)
{
...seed stuff and save it...
WebSecurity.InitializeDatabaseConnection("TrackerContext", "User", "Id", "UserName", autoCreateTables: true);
}
}
Through debugging it does not throw any error and I can confirm it is hitting this line of code. My User model looks like this:
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public PasswordQuestion PasswordQuestion{ get; set; }
public string PasswordAnswer { get; set; }
public string Type { get; set; }
}
From everything I have read, I thought this should be all I need to do to get this working, but I have two problems:
No membership tables are being loaded
My Config seems to be throwing an error even though I am referencing the WebMatrix.WebData dll
Here is the config section:
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear/>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear/>
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
What am I missing here?

As far as I can see, you're missing the
public DbSet<User> User{ get; set; }
in your context class. You'll have to do this for every table you want Migrations to create for you in your database.

1) Did you check your ConnectionString? Should be something like this:
<connectionStrings>
<add name="DefaultConnection" connectionString="data source=SERVER;initial catalog=DATABASE;user id=USER;password=PASSWORD;" providerName="System.Data.SqlClient" />
</connectionStrings>
Furthermore you should have this in your config too:
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
2) Check your references. System.Web.Webpages should be there and CopyLocal should be set to true. Then check your .NET Framework Version as well (4.0, no Client Edition)
Hope this helps.

Related

Database context didn't see any records in datatable in base

I'm creating an ASP.NET MVC application which uses a PostgreSql database. Model classes are in a different class library. For access to database I'm using Entity Framework + Npgsql.Entityframework in the class library. Also i added same links to main project. Configuration settints are in web.config of main project:
<configSections>
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="Npgsql.NpgsqlServices, Npgsql.EntityFramework" />
<providers>
<provider invariantName="Npgsql"
type="Npgsql.NpgsqlServices, Npgsql.EntityFramework" />
</providers>
</entityFramework>
<connectionStrings>
<add name="NpgsqlContext"
providerName="Npgsql"
connectionString="Server=127.0.0.1;User Id=BaseId;Password=BasePass;Port=5432;Database=Base;" />
</connectionStrings>
<system.data>
<DbProviderFactories>
<add name="Npgsql Data Provider"
invariant="Npgsql"
support="FF"
description=".Net Framework Data Provider for Postgresql"
type="Npgsql.NpgsqlFactory, Npgsql" />
</DbProviderFactories>
</system.data>
My database context has right connectionn string
(PORT=5432;KRBSRVNAME=name;TIMEOUT=15;POOLING=True;MINPOOLSIZE=1;MAXPOOLSIZE=20;COMMANDTIMEOUT=20;COMPATIBLE=2.2.7.0;HOST=127.0.0.1;USER ID=BasePass;PASSWORD=BasePass;DATABASE=Base),
but didn't see any records in datatable in base. Meanwhile records are there.
I created database and some tables in pgAdmin. To access to tables i use classes:
public class NpgsqlContext : DbContext
{
public NpgsqlContext(): base(nameOrConnectionString: "NpgsqlContext")
{
}
public DbSet<BaseArticle> BaseArticles { get; set; }
}
[Table("ARTICLE", Schema = "public")]
public class BaseArticle
{
[Key]
[Column("ID")]
public int Id { get; set; }
[Column("DATETIME")]
public DateTime DateTime { get; set; }
[Column("TITLE")]
public string Title { get; set; }
[Column("BODY")]
public string Body { get; set; }
}
NpgsqlContext object is created normally, but DbSet BaseArticle's count equals 0.
Where can i have an error?
And also - in ASP.NET MVC generally impossible to achieve loose coupling between the parts of the application?
For the solution of my problem i needed to open connection to base in constructor of context:
this.Database.Connection.Open();

Entity Framework Not Showing Database

Working with Code First feature of Entity Framework 4.1 using an ASP.NET MVC 3 project.
However the database (SQL Server 2008 R2) does not automatically create the table mapping on application startup. Any ideas on how to make it do so?
using System;
using System.Data.Entity;
namespace MvcMovie.Models {
public class Movie {
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
Also there is this database context class
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
}
In global.asax file
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
Kindly help?? I am a beginner? Even you could suggest some reading material for asp.net it would be of great help ?
Here is a good overview. You can use a config entry:
<entityFramework>
<contexts>
<context type="ContosoUniversity.DAL.SchoolContext, ContosoUniversity">
<databaseInitializer type="ContosoUniversity.DAL.SchoolInitializer, ContosoUniversity" />
</context>
</contexts>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
Or set it up via code as mentioned here:
Database.SetInitializer(new DropCreateDatabaseAlways<BlogContext>());
using (var db = new BlogContext())
{
db.Database.Initialize(false);
...
}

MVC3 Code First Not Creating Database

I've been doing this Movies database tutorial for MVC3 with Code First, but when I try to access the /Movies page I get the error
"The network path was not found".
I don't think I missed any steps in the tutorial.
I created my Movie model
namespace Movies.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseData { get; set; }
public string Genre { get; set; }
public Decimal Price { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
}
I added the connection string as well
<add name="MovieDBContext" connectionString="Data Source=|DataDirectory|Movies.sdf" providerName="System.Data.SqlClient"/>
In the tutorial the connection string is this, but it was giving me errors trying to create the controller so I found somewhere to change it to the one above, which allows me to create the controller fine but then get the network path error.
<add name="MovieDBContext" connectionString="Data Source=|DataDirectory|Movies.sdf" providerName="System.Data.SqlServerCe.4.0"/>
Did you try?
new DbContext("MovieDBContext")
http://msdn.microsoft.com/en-us/library/gg679467(v=vs.103).aspx
Did you try to emit at least a select 1; from your code?
<system.data>
<DbProviderFactories>
<add name="SQL Server Compact Edition Data Provider"
invariant="System.Data.SqlServerCe"
description=".NET Framework Data Provider for Microsoft SQL Server Compact Edition"
type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/>
</DbProviderFactories>
See also Entity Framework on SQL Server CE without driver install
i think you have forgot to add
Integrated Security=SSPI

Can't add a controller in asp.net MVC3 EF code first

I have created a new project from template. I used windows phone cloud toolkit template which server side is a regular asp.net mvc3 project with EF 4.1 code first.
My datacontext is called SqlDataContext and has the following constructor:
public SqlDataContext()
: base(ConfigReader.GetConfigValue("SqlSampleDataContextConnectionString"))
{
}
public DbSet<SqlSampleData> SqlSampleData { get; set; }
My connection string defined in web.config as:
<connectionStrings>
<add name="ApplicationServices" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=true;User Instance=true;AttachDBFilename=|DataDirectory|\WPCloudApp26.mdf;Initial Catalog=WPCloudApp26;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
I have added a new model called Report and now i want to create new controller with the add controller wizard, using my new Report model and the SqlDataContext. when I try to create i get the following error:
Unable to retrieve metadata for 'WPCloudApp1.Web.Models.Report'.
The 'SqlSampleDataContextConnectionString' setting is not available.
Parameter name: key
And it fails to create the new controller.
What am i doing wrong ? My background in this topic very scarce so please try to make it as simple as possible.
My Report class:
namespace WPCloudApp26.Web.Models
{
using System;
using System.ComponentModel.DataAnnotations;
// Summary:
// Sample Entity Framework 4.1 data class for SQL Azure.
// Using EF 4.1 Code-First, the database structure will be created to mirror this class properties.
// For more information, visit the ADO.NET Entity Framework website at http://msdn.microsoft.com/data/aa937723
public class Report
{
[Key]
public int Id { get; set; }
public string UserId { get; set; }
public string Description { get; set; }
public DateTime Date { get; set; }
public bool IsPublic { get; set; }
}
}
Thanks.
Edit:
I have no problem running the application, only adding a new controller.
Try to replace :
<connectionStrings>
<add name="ApplicationServices" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=true;User Instance=true;AttachDBFilename=|DataDirectory|\WPCloudApp26.mdf;Initial Catalog=WPCloudApp26;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
By:
<connectionStrings>
<add name="SqlDataContext" connectionString="Data Source=.\SQLEXPRESS;Integrated Security=true;User Instance=true;AttachDBFilename=|DataDirectory|\WPCloudApp26.mdf;Initial Catalog=WPCloudApp26;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>
The context should be the value stored in the web.config

asp.net mvc custom profile provider

I want to have custom profile provider in my asp.net mvc 3 app. The problem is, that I don't want to use default DB that is generated by ASP.NET Membership/Role/Profile provider, mainly because authentication is already done with WebService and DBs already exist.
I want to user profile properties to populate them and use within different areas of the site.
I took a look at this example (How to assign Profile values?) but I am getting this error:
An attempt to attach an auto-named database for file
C:\Projects\FWManager\App_Data\aspnetdb.mdf failed. A database with
the same name exists, or specified file cannot be opened, or it is
located on UNC share.
Here is the web.config
<profile inherits="FWMembership.Membership.FWProfileProvider" defaultProvider="AspNetSqlProfileProvider" automaticSaveEnabled="false" enabled="true">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
This is my custom class
public class FWProfileProvider : ProfileBase
{
[SettingsAllowAnonymous(false)]
public string FirstName
{
get { return base["FirstName"] as string; }
set { base["FirstName"] = value; }
}
[SettingsAllowAnonymous(false)]
public string LastName
{
get { return base["LastName"] as string; }
set { base["LastName"] = value; }
}
[SettingsAllowAnonymous(false)]
public int? UserID
{
get { return base["UserID"] as int?; }
set { base["UserID"] = value; }
}
[SettingsAllowAnonymous(false)]
public string UserCompany
{
get { return base["UserCompany"] as string; }
set { base["UserCompany"] = value; }
}
[SettingsAllowAnonymous(false)]
public string Email
{
get { return base["Email"] as string; }
set { base["Email"] = value; }
}
public StringCollection Entitlements
{
get { return base["Entitlements"] as StringCollection; }
set { base["Entitlements"] = value; }
}
public string username;
public FWProfileProvider()
{
}
public FWProfileProvider(string username)
{
this.username = username;
}
static public FWProfileProvider CurrentUser
{
get
{
return (FWProfileProvider)
(ProfileBase.Create("Joe"));
}
}
}
The key is to avoid using asp.net default membership tables.
Any ideas?
EDIT:
Forgot to add - this web application, but profile provider is placed in the class library project within same soulution:
Solution
|->FWProfile (class library project)
|->UI (asp.net mvc 3 web application)
I think you have to write your own MemberShip Provider as well. Your web.config refers to the default asp.net membership provider. How to write a Membership provider you can find here custom membership provider
The default membership provider uses a connection string into a locally installed SQL Express database and that causes your error.
Your web.config would look like this:
<membership defaultProvider="MyCustomMembershipProvider">
<providers>
<clear />
<add name="MyCustomMembershipProvider"
type="FWMembership.Membership.MyCustomMembershipProvider"
enablePasswordRetrieval="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Clear"/>
</providers>
</membership>
<profile defaultProvider="MyProfileProvider" enabled="true">
<providers>
<clear/>
<add name="MyProfileProvider" type="FWMembership.Membership.FWProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
Hope this helps.

Resources