MVC Code First Database Without Data: Where is the Database? - asp.net-mvc

Got three simple classes
namespace MVC_Risk.Models
{
public class Customer
{
public string SrcSys { get; set; }
public string CustumerID { get; set; }
public string CustNm { get; set; }
public virtual ICollection<Account> Accounts { get; set; }
}
}
namespace MVC_Risk.Models
{
public class Account
{
public string SrcSys { get; set; }
public string CustomerID { get; set; }
public string AccountID { get; set; }
public virtual ICollection<Balance> Balances { get; set; }
public virtual Customer Customers { get; set; }
}
}
namespace MVC_Risk.Models
{
public class Balance
{
public int BalanceID { get; set; }
public int EntryNo { get; set; }
public DateTime RepDt { get; set; }
public string SrcSys { get; set; }
public string CustIdX { get; set; }
public string CustNm { get; set; }
public string AccountID { get; set; }
public string BrId { get; set; }
public string SegId { get; set; }
public string ProdId { get; set; }
public decimal? PrOs { get; set; }
public decimal? MupRec { get; set; }
public virtual Account Accounts { get; set; }
}
}
Attempting to learn Fluent API auto-generated keys concept.
Context File:
namespace MVC_Risk.DAL
{
public class RiskContext : DbContext
{
public RiskContext() : base("RiskyConnectionString")
{
}
public DbSet<Customer> Customers;
public DbSet<Account> Accounts;
public DbSet<Balance> Balances;
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
Initializer File (Requiring a clean Database (i.e. without data):
namespace MVC_Risk.DAL
{
public class RiskyInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<RiskContext>
{
protected override void Seed(RiskContext context)
{
}
}
}
Web.Config file as:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="RiskyConnectionString" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=RiskyDatabase1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.2" />
<httpRuntime targetFramework="4.6.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
</system.webServer>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<entityFramework>
<contexts>
<context type="MVC_Risk.DAL.RiskContext, MVC_Risk">
<databaseInitializer type="MVC_Risk.DAL.RiskyInitializer, MVC_Risk" />
</context>
</contexts>
<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>
</configuration>
Upon Building and running the site launches but database not found on (LocalDb)\MSSQLLocalDB?

Did you run your initial Entity Framework Migration?

Related

EntityFramework.Extended library do not work with connection string

Let me say,my database is mysql,Reference EntityFramework.Extended library in order to support batch update in Entity Framework .But EntityFramework.Extended library do not work with connection string in my DbContext
public MyContext() :base("DefaultConnection") this work!
//this does not work!
public MyContext() : base("server=localhost;user id=root;password=123456;database=AA;")
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="server=127.0.0.1;user id=root;password=123456;persist security info=True;database=AA;charset=utf8;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
</system.webServer>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v12.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider></providers>
</entityFramework>
</configuration>
MyContext.cs
[DbConfigurationType(typeof(DbContextConfiguration))]
public class MyContext : DbContext
{
public DbSet<Users> Users { get; set; }
//public MyContext() :base("DefaultConnection") this work!
public MyContext() : base("server=localhost;user id=root;password=123456;database=AA;") //this do not work!
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("");
}
}
public class DbContextConfiguration : DbConfiguration
{
public DbContextConfiguration()
{
EntityFramework.Locator.Current.Register<EntityFramework.Batch.IBatchRunner>(() => new MySqlBatchRunner());
}
}
HomeController.cs
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
using (var db = new MyContext())
{
var list = db.Users.ToList();
}
return View();
}
}

ASP.MVC: Error running selected code generator "documentId did not come from visual studio workspace" Parameter id: documentId

I'm trying to use a code first approach in EF 6.1.3 with visual studio 2015. Everything went well and the project builds, however if I want to add a "New scaffold item" -> "MVC Controller with Views, using EF" it keeps giving me the following error:
Error running selected code generator.
The given documentId did not come from visual studio workspace"
Parameter id: documentId
If I use any of the other Controller it works fine, but I don't want to type out all the code by myself. I have the following files Any help will be much appreciated. Cheers!
----------------------------------------------------------------------------------------------------- MODELS ---------------------------------------------------
Models -> Course.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace ContosoUniversity.Models
{
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Key]
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
}
Models -> Student.cs
using System;
using System.Collections.Generic;
namespace ContosoUniversity.Models
{
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual IReadOnlyCollection<Enrollment> Enrollments { get; set; }
}
}
Model -> Enrollment.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace ContosoUniversity.Models
{
public enum Grade
{
A,B,C,D,E,F
}
public class Enrollment
{
[Key]
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public Grade? Grade { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}
}
DAL -> SchoolContext.cs
using ContosoUniversity.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace ContosoUniversity.DAL
{
public class SchoolContext : DbContext
{
public SchoolContext() : base("SchoolContext")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
DAL -> SchoolInitializer (insitialize data file)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using ContosoUniversity.Models;
namespace ContosoUniversity.DAL
{
public class SchoolInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<SchoolContext>
{
protected override void Seed(SchoolContext context)
{
var students = new List<Student>
{
new Student { FirstMidName="Carson", LastName="Alexander", EnrollmentDate=DateTime.Parse("2005-09-01") },
new Student { FirstMidName="Meredith", LastName="Alonso", EnrollmentDate=DateTime.Parse("2002-09-01") },
new Student { FirstMidName="Arturo", LastName="Anand", EnrollmentDate=DateTime.Parse("2003-09-01") },
new Student { FirstMidName="Gytis", LastName="Barzdukas", EnrollmentDate=DateTime.Parse("2002-09-01") },
new Student { FirstMidName="Yan", LastName="Li", EnrollmentDate=DateTime.Parse("2002-09-01") },
new Student { FirstMidName="Peggy", LastName="Justice", EnrollmentDate=DateTime.Parse("2001-09-01") },
new Student { FirstMidName="Laura", LastName="Norman", EnrollmentDate=DateTime.Parse("2003-09-01") },
new Student { FirstMidName="Nino", LastName="Olivetto", EnrollmentDate=DateTime.Parse("2005-09-01") }
};
students.ForEach(s => context.Students.Add(s));
context.SaveChanges();
var courses = new List<Course>
{
new Course { CourseID=1050, Title="Chemistry", Credits=3, },
new Course { CourseID=4022, Title="Micro economics", Credits=3, },
new Course { CourseID=4041, Title="Macro economics", Credits=3, },
new Course { CourseID=1045, Title="Calculus", Credits=4, },
new Course { CourseID=3141, Title="Trigonometry", Credits=4, },
new Course { CourseID=2021, Title="Composition", Credits=3 },
new Course { CourseID=2042, Title="Literature", Credits=4 }
};
courses.ForEach(c => context.Courses.Add(c));
context.SaveChanges();
var enrollements = new List<Enrollment>
{
new Enrollment { StudentID=1, CourseID=1050, Grade=Grade.A },
new Enrollment { StudentID=1, CourseID=4022, Grade= Grade.C },
new Enrollment { StudentID=1, CourseID=4041, Grade= Grade.B },
new Enrollment { StudentID=2, CourseID=1045, Grade=Grade.B },
new Enrollment { StudentID=2, CourseID=3141, Grade=Grade.F},
new Enrollment { StudentID=2, CourseID=2021, Grade=Grade.F },
new Enrollment { StudentID=3, CourseID=1050 },
new Enrollment { StudentID=4, CourseID=1050 },
new Enrollment { StudentID=4, CourseID=4022, Grade= Grade.F },
new Enrollment { StudentID=5, CourseID=4041, Grade= Grade.C },
new Enrollment { StudentID=6, CourseID=1045 },
new Enrollment { StudentID=7, CourseID=3441, Grade=Grade.A },
};
enrollements.ForEach(e => context.Enrollments.Add(e));
context.SaveChanges();
}
}
}
Web config in the root
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0; Initial Catalog=ContosoUniversity1; Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
</system.webServer>
<entityFramework>
<contexts>
<context type="ContosoUniversity.DAL.SchoolContext, ContosoUniversity">
<databaseInitializer type="ContosoUniversity.DAL.SchoolInitializer, ContosoUniversity"></databaseInitializer>
</context>
</contexts>
<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>
</configuration>
I've run into this problem today, I just unload/reload (right-click on the project in VisualStudio "Unload Project", then again right click "Reload project") the project in VisualStudio and then Rebuild the project and I was able to create the Controller.

MVC Project users table location

I am making a simple MVC Cookbook web application to store recipes I make and give them a rating. It's more of a learning project then anything else. I used microsoft's Contoso University code first example located
Here
My project is simpler, they have 3 entity classes (student, enrollment, course) where as I only have one (recipe)
As I said before, this was a code first approach, so I designed my recipe class
Recipe.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Recipes.Models
{
public class Recipe
{
public int RecipeID { get; set; }
public string Name { get; set; }
public DateTime EntryDate { get; set; }
public int Calories { get; set; }
public int Protein { get; set; }
public int Carbs { get; set; }
public int Fat { get; set; }
public bool Spicy{ get; set; }
}
}
And created a DAL (data access layer) folder that contains my database context and initiator with some test data.
RecipeContext.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Recipes.Models;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace Recipes.DAL
{
public class RecipeContext : DbContext
{
public RecipeContext() : base("RecipeContext")
{
}
public DbSet<Recipe> Recipes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
RecipeInitializor.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Recipes.Models;
namespace Recipes.DAL
{
public class RecipeInitializor : System.Data.Entity.DropCreateDatabaseIfModelChanges<RecipeContext>
{
protected override void Seed(RecipeContext context)
{
var Recipes = new List<Recipe>
{
new Recipe {RecipeID = 111, Name = "Chicken Fajitas", Calories = 500, Carbs = 35, Fat = 10, Protein = 35, EntryDate = DateTime.Parse("2016-08-01"), Spicy = true},
new Recipe {RecipeID = 112, Name = "Dijon Chicken", Calories= 415, Carbs = 10, Fat = 5, Protein = 30, EntryDate = DateTime.Parse("2016-09-01"), Spicy = false},
new Recipe {RecipeID = 113, Name = "Turkey Chili", Calories = 475, Carbs = 25, Fat = 5, Protein = 40, EntryDate = DateTime.Parse("2016-09-05"), Spicy = true },
new Recipe {RecipeID = 114, Name = "Beef Stew", Calories= 515, Carbs = 28, Fat = 15, Protein = 30, EntryDate = DateTime.Parse("2016-07-06"), Spicy = false }
};
Recipes.ForEach(s => context.Recipes.Add(s));
context.SaveChanges();
//base.Seed(context);
}
}
//class RecipeInitializor
//{
//}
}
When I ran this project, it created a table for me, called recipes.
My question is, where are the users stored? When creating the project, I decided to keep individual accounts for the log in system. I've created one user with a username and password and I can log into the site using this so I know it has to be stored somewhere. When I google the issue, people keep saying its located in the App_Data folder but there is nothing inside mine.
So where is the database for the users? And how can I have it placed in the same location as my Recipes database?
EDIT Requested updates
IdentityModel.cs
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace Recipes.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="RecipeContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Recipes1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<contexts>
<context type="Recipes.DAL.RecipeContext, Recipes">
<databaseInitializer type="Recipes.DAL.RecipeInitializor, Recipes"></databaseInitializer>
</context>
</contexts>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
ADDITIONAL EDIT
I clicked 'show all files' in the solution explorer but still don't see anything.
I even navigated to the App_data folder in File explorer, turned on 'view hidden files' and still don't see anything. I think this folder is empty
EDIT
The database is most likely in your App_Data folder, but not included in your project. Click on "Show all Files" at the top of the solution explorer to view it.
In order to get this database in the same location as your Recipies database, you'll need to add another connection string and modify your IdentityModels.cs class (below) to use this new connection string (this will create the same database as it does currently, just in the location you indicate).
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("UsersConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
EDIT
If you want all the tables from the ApplicationDBContext to be included in your Recipies database (you weren't specific), then you need to make sure your RecipeContext inherits from IdentityDbContext and create a static method call Create:
public class RecipeContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Recipe> Recipes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public static RecipeContext Create()
{
return new RecipeContext();
}
}
and modify your ApplicationUserManager (IdentityConfig.cs) to use your RecipeContext in the Create method:
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<RecipeContext>()));
and modify the ConfigureAuth method in Startup.Auth.cs
app.CreatePerOwinContext(RecipeContext.Create);
Edit 2
Make sure you include this line in your OnModelCreating override:
base.OnModelCreating(modelBuilder);
Based on the connection string in your web.config, your database is in the LocalDB.
LocalDB is a lightweight version of the SQL Server Express Database Engine that is targeted for program development. LocalDB starts on demand and runs in user mode, so there is no complex configuration. By default, LocalDB database creates “*.mdf” files in the C:/Users/ directory.

WCF SOAP to WCF REST conversion in MVC giving end point error

Problem Statement:
Performing MVC CRUD operations using WCF Service.Everything was working fine with SOAP,but when i changed from SOAP to REST it is giving end point error.I suspect that there might be some problem with my webconfig..!!!
Exception Details:
"There was no endpoint listening at http://localhost:8733/Design_Time_Addresses/ALCMS.MasterConfigurationService/Service1/InsertAssetType that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details."
WCF REST service is hosting properly and it is running.I'm getting the exception mentioned above in WCF REST Service method calls in controller like :
objSvcMasterConfig.InsertAssetType(objAssetTypeDC);
objSvcMasterConfig.UpdateAssetType(objAssetTypeDC);
objSvcMasterConfig.DeleteAssetType(objAssetTypeDC);
What i'm doing wrong??
I'm having two projects in Solution
WCF Service library
MVC Razor application
1. WCF Service Library:
IService1.cs
Data Contract:
[DataContract]
public class AssetTypeDC
{
[DataMember]
public int ID { get; set; }
[DataMember]
public int AssetTypeID { get; set; }
[DataMember]
public string Name { get; set; }
}
Service Contract:
[ServiceContract]
public interface IService1
{
#region Asset Type
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "InsertAssetType")]
bool InsertAssetType(AssetTypeDC objAssetTypeDC);
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "UpdateAssetType")]
[OperationContract]
bool UpdateAssetType(AssetTypeDC objAssetTypeDC);
[WebInvoke(Method = "DELETE",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "DeleteAssetType")]
[OperationContract]
bool DeleteAssetType(AssetTypeDC objAssetTypeDC);
#endregion
}
Service.cs
public bool InsertAssetType(AssetTypeDC objAssetTypeDC)
{
try
{
objAssetType.ID = objAssetTypeDC.ID;
objAssetType.AssetTypeID = objAssetTypeDC.AssetTypeID;
objAssetType.Name = objAssetTypeDC.Name;
dbEntity.AssetTypes.Attach(objAssetType);
var entry = dbEntity.Entry(objAssetType);
dbEntity.AssetTypes.Add(objAssetType);
dbEntity.SaveChanges();
return true;
}
catch
{
return false;
}
}
public bool UpdateAssetType(AssetTypeDC objAssetTypeDC)
{
try
{
objAssetTypeID = ID;
objAssetType.AssetTypeID = objAssetTypeDC.AssetTypeID;
objAssetType.Name = objAssetTypeDC.Name;
dbEntity.AssetTypes.Attach(objAssetType);
var entry = dbEntity.Entry(objAssetType);
entry.Property(e => e.Name).IsModified = true;
dbEntity.SaveChanges();
return true;
}
catch
{
return false;
}
}
public bool DeleteAssetType(AssetTypeDC objAssetTypeDC)
{
try
{
objAssetType.AssetTypeID = objAssetTypeDC.AssetTypeID;
objAssetType.ID = objAssetTypeDC.ID;
dbEntity.AssetTypes.Attach(objAssetType);
dbEntity.Entry(objAssetType).State = EntityState.Deleted;
dbEntity.SaveChanges();
return true;
}
catch
{
return false;
}
}
App.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<services>
<service name="ALCMS.MasterConfigurationService.Service1" behaviorConfiguration="ALCMS.MasterConfigurationService.Service1Behaviour">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/ALCMS.MasterConfigurationService/Service1/" />
</baseAddresses>
</host>
<endpoint address="" binding="webHttpBinding" contract="ALCMS.MasterConfigurationService.IService1" behaviorConfiguration="ALCMS.MasterConfigurationService.RESTEndpointBehaviour">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="ALCMS.MasterConfigurationService.RESTEndpointBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ALCMS.MasterConfigurationService.Service1Behaviour">
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<connectionStrings><add name="DB_V2Entities" connectionString="metadata=res://*/Entities.MasterConfigurationEntity.csdl|res://*/Entities.MasterConfigurationEntity.ssdl|res://*/Entities.MasterConfigurationEntity.msl;provider=System.Data.SqlClient;provider connection string="data source=SQL-PC\SQLEXPRESS;initial catalog=DB_V2;user id=sa;password=Sql#123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings></configuration>
2.MVC Application
Controller:
Insert Operation:
[HttpPost]
public ActionResult Create(AssetTypeModel assettypemodel)
{
if (ModelState.IsValid)
{
objAssetTypeDC.ID = 1;
objAssetTypeDC.AssetTypeID = assettypemodel.ID;
objAssetTypeDC.Name = assettypemodel.Name;
objSvcMasterConfig.InsertAssetType(objAssetTypeDC);
return RedirectToAction("Index");
}
return View(assettypemodel);
}
Update Operation:
[HttpPost]
public ActionResult Edit(AssetTypeModel assettypemodel, int id, int ID)
{
if (ModelState.IsValid)
{
objAssetTypeDC.ID = assettypemodel.ID = ID;
objAssetTypeDC.AssetTypeID = assettypemodel.AssetTypeID = id;
objAssetTypeDC.Name = assettypemodel.Name;
objSvcMasterConfig.UpdateAssetType(objAssetTypeDC);
return RedirectToAction("Index");
}
return View(assettypemodel);
}
Delete Operation:
public ActionResult Delete(int id = 0, int ID = 0)
{
AssetTypeModel assettypemodel = db.AssetType.Find(id, ID);
if (assettypemodel == null)
{
return HttpNotFound();
}
return View(assettypemodel);
}
Web.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DB" connectionString="Data Source=SQL-PC\SQLEXPRESS;initial catalog=DB_V2;Persist Security Info=True;User ID=sa;Password=Sql#123;Pooling=False;" providerName="System.Data.SqlClient" />
<add name="DBEntities" connectionString="metadata=res://*/Entities.WebEntity.csdl|res://*/Entities.WebEntity.ssdl|res://*/Entities.WebEntity.msl;provider=System.Data.SqlClient;provider connection string="data source=SQL\SQLEXPRESS;initial catalog=DB_V2;user id=sa;Password=Sql#123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5"><assemblies><add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /></assemblies></compilation>
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Login" protection="All" timeout="2880" />
</authentication>
<sessionState mode="InProc" timeout="30" stateConnectionString="tcpip=SQL-PC\SQLEXPRESS,1433" cookieless="false" regenerateExpiredSessionId="false" />
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebHttpBinding_IService1" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="ALCMS.MasterConfigurationService.RESTEndpointBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://localhost:8733/Design_Time_Addresses/ALCMS.MasterConfigurationService/Service1/" binding="webHttpBinding" bindingConfiguration="WebHttpBinding_IService1" behaviorConfiguration="ALCMS.MasterConfigurationService.RESTEndpointBehaviour" contract="MasterConfigurationServiceReference.IService1" name="WebHttpBinding_IService1" />
</client>
</system.serviceModel>
</configuration>
Mr Vishal,
Instead of converting, you can develop in REST only.

MVC3 Could not find schema information for the element 'entityFramework' when using EF 5.0

I found the following messages in my we.config file after looking for a couple of minutes to see why my database was not seeding.
The complete message list is as follows:
Message 1 Could not find schema information for the element 'entityFramework'.
Message 2 Could not find schema information for the element 'defaultConnectionFactory'.
Message 3 Could not find schema information for the at'type'.
Now I am extremely new to MVC, and this is my first application that I have ever built. I want to utilize the Code First Technologies available to create the database from my models that I have built.
Here is an Example of a model I Created:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace TNTMVC.Models.UECDECZA.BaseTables
{
public class Actions
{
[Key]
public int ActionID { get; set; }
[Timestamp]
public DateTime ActionDateCreated { get; set; }
[Required]
[DefaultValue(true)]
public bool ActionActive { get; set; }
[Required]
public string ActionName { get; set; }
[Required]
[DefaultValue(true)]
public bool ActionRequiresComponents { get; set; }
[Required]
[DefaultValue(1000)]
public int ActionListOrder { get; set; }
}
}
Then I created my DB Context Class which looks like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using TNTMVC.Models.UECDECZA.BaseTables;
using TNTMVC.Models.UECDECZA.DataTables;
namespace TNTMVC.Models.UECDECZA
{
public class UecdeczaContext : DbContext
{
public DbSet<Actions> Actions { get; set; }
public DbSet<Application> Application { get; set; }
public DbSet<Area> Area { get; set; }
}
}
And here is my Web.Config file:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
<add name="UecdeczaContext" connectionString="Data Source=.\SQLExpress;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="System.Data.Entity" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
This is suppose to be a successful model implementation right? But it doesn't seem to work at all. It's not seeding my Database and it's not working :(
I have also Asked the same Question on ASP forumns: My ASP Forum Question
You don't seem to have an initializer (other than the default one) that is calling a Seed() method. See Julia Lerman's blog post on seeding for more info. You need something like:
public class UecdeczaInitializer : DropCreateDatabaseIfModelChanges<UecdeczaContext >
{
protected override void Seed(UecdeczaContext context)
{
new List<Actions>
{
new Actions
{
ActionName = "My action name"
}
}
}.ForEach(b => context.Blogs.Add(b));
base.Seed(context); }
}
You might need to stick more properties in there to seed your Actions entities, but that's the basic idea.

Resources