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

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

Related

ASP.NET code first doesn't create DB or Tables

I'm trying to add a new connection to database in an ASP.NET application, and I'm trying to use code-first initialization.
For now, that are my connection strings:
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Auth-20211221042302.mdf;Initial Catalog=aspnet-Auth-20211221042302;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="DriveMeConnection"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DriveMe-App-20211231001122.mdf;Initial Catalog=DriveMe-App-20211231001122;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
The first, DefaultConnection, was generated for the ASP.NET authentication, and works well.
The second, DriveMeConnection, is the database I want to create from my code-first model.
So, I created a new DbContext as usual:
public class DatabaseContext : DbContext
{
public DbSet<Azienda> Aziende;
public DbSet<ClientePrivato> ClientiPrivati;
public DbSet<Fornitore> Fornitori;
public DbSet<Auto> ParkAuto;
public DbSet<Guidatore> Guidatori;
public DbSet<Pratica> Pratiche;
public DatabaseContext() : base("name=DriveMeConnection")
{
}
}
(there's no difference if I use base("name=DriveMeConnection") or base("DriveMeConnection")).
When I am trying to read something, for example
using (DatabaseContext db = new DatabaseContext())
{
List<Fornitore> lst = db.Fornitori.ToList();
}
Fornitori table was not created. In this case, the whole database wasn't created.
I tried to add
Database.SetInitializer<DatabaseContext>(new CreateDatabaseIfNotExists<DatabaseContext>());
inside the DatabaseContext constructor, but nothing changes.
I tried to add
this.Database.CreateIfNotExists();
inside the DatabaseContext constructor, the database was created, but the tables aren't there.
I tried to force initialization with:
using (DatabaseContext db = new DatabaseContext())
{
db.Database.Initialize(force: true);
}
This creates the database, but it is still empty without tables.
What did I miss?
I finally solved, without migrations that I don't need for now, I only call this function at startup.
public static void FirstConfiguration()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DatabaseContext>());
var context = new DatabaseContext();
context.Database.Initialize(true);
}
And in the DbContext, the dataset need to be properties with the get and set method:
public class DatabaseContext : DbContext
{
public DbSet<Azienda> Aziende { get; set; }
public DbSet<ClientePrivato> ClientiPrivati { get; set; }
public DbSet<Fornitore> Fornitori { get; set; }
public DbSet<Auto> ParkAuto { get; set; }
public DbSet<Guidatore> Guidatori { get; set; }
public DbSet<Pratica> Pratiche { get; set; }
public DatabaseContext() : base("name=DriveMeConnection")
{
}
}

ASP.NET connection string to SQL Server

Well I was developing an ASP.NET webforms app in Visual Studio and it worked well. It has 2 SQL Server connection strings, one for ASP.NET Identity and the other for my own tables. Then I wanted to test my app on a real server. So I changed the connection strings to this:
<add name="DefaultConnection"
connectionString="Data Source=WIN-9I87AF3QUO9;Initial Catalog=aspnet-AdManager-20141230074246;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="StracturesConnection"
connectionString="Data Source=WIN-9I87AF3QUO9;Initial Catalog=aspnet-AdManager-20141230074246;Integrated Security=True"
providerName="System.Data.SqlClient" />
Now the DefaultConnection works well. but the second one doesn't.
I get an error:
A network-realated or instance-specific error
here is the code of my DbContext
public class StructureDbContext : DbContext
{
public StructureDbContext()
: base("StructuresConnection")
{
}
public DbSet<Structure> Structures { get; set; }
public DbSet<StructureType> StructureTypes { get; set; }
public DbSet<Reservation> Reservations { get; set; }
}
and this one is the db initializer:
public class DatabaseInitializer : DropCreateDatabaseIfModelChanges<StructureDbContext>
{
protected override void Seed(StructureDbContext context)
{
Structure s = new Structure();
s.StructureTypeID = null;
s.Description = "Test";
s.CityID = 45;
s.Address = "test";
s.Price = 400;
context.Structures.Add(s);
StructureType t = new StructureType();
t.Name = "بیلبورد";
context.StructureTypes.Add(t);
}
}
}
Well the problem is a miss spelling. in the connection string I wrote "Stractures" and this is wrong! sorry for wasting your time. I should go and check why this works on visual studio!

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

SimpleMembershipProvider not adding tables to my database

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.

Unable to Retrieve Metadata

MVC4 + Entity Framework 4.4 + MySql + POCO/Code First
I'm setting up the above configuration .. here are my classes:
namespace BTD.DataContext
{
public class BTDContext : DbContext
{
public BTDContext()
: base("name=BTDContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//modelBuilder.Conventions.Remove<System.Data.Entity.Infrastructure.IncludeMetadataConvention>();
}
public DbSet<Product> Products { get; set; }
public DbSet<ProductImage> ProductImages { get; set; }
}
}
namespace BTD.Data
{
[Table("Product")]
public class Product
{
[Key]
public long ProductId { get; set; }
[DisplayName("Manufacturer")]
public int? ManufacturerId { get; set; }
[Required]
[StringLength(150)]
public string Name { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Required]
[StringLength(120)]
public string URL { get; set; }
[Required]
[StringLength(75)]
[DisplayName("Meta Title")]
public string MetaTitle { get; set; }
[DataType(DataType.MultilineText)]
[DisplayName("Meta Description")]
public string MetaDescription { get; set; }
[Required]
[StringLength(25)]
public string Status { get; set; }
[DisplayName("Create Date/Time")]
public DateTime CreateDateTime { get; set; }
[DisplayName("Edit Date/Time")]
public DateTime EditDateTime { get; set; }
}
[Table("ProductImage")]
public class ProductImage
{
[Key]
public long ProductImageId { get; set; }
public long ProductId { get; set; }
public long? ProductVariantId { get; set; }
[Required]
public byte[] Image { get; set; }
public bool PrimaryImage { get; set; }
public DateTime CreateDateTime { get; set; }
public DateTime EditDateTime { get; set; }
}
}
Here is my web.config setup...
<connectionStrings>
<add name="BTDContext" connectionString="Server=localhost;Port=3306;Database=btd;User Id=root;Password=mypassword;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
The database AND tables already exist...
I'm still pretty new with mvc but was using this tutorial
The application builds fine... however when I try to add a controller using Product (BTD.Data) as my model class and BTDContext (BTD.DataContext) as my data context class I receive the following error:
Unable to retrieve metadata for BTD.Data.Product using the same
DbCompiledModel to create context against different types of database
servers is not supported. Instead, create a separate DbCompiledModel
for each type of server being used.
I am at a complete loss - I've scoured google with almost every different variation of that error message above I can think of but to no avail.
Here are the things i can verify...
MySql is working properly
I'm using MySql Connector version 6.5.4 and have created other ASP.net web forms + entity framework applications with ZERO problems
I have also tried including/removing this in my web.config:
<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.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
I've literally been working on this bug for days - I'm to the point now that I would be willing to pay someone to solve it.. no joke... I'd really love to use MVC 4 and Razor - I was so excited to get started on this, but now i'm pretty discouraged - I truly appreciate any help/guidance on this!
Also note - i'm using Entityframework from Nuget...
Another Note
I was using the default visual studio template that creates your MVC project with the account pages and other stuff. I JUST removed all references to the added files because they were trying to use the "DefaultConnection" which didn't exist - so i thought those files may be what was causing the error - however still no luck after removing them -
I just wanted to let everyone know i'm using the visual studio MVC project template which pre-creates a bunch of files. I will be trying to recreate this all from a blank MVC project which doesn't have those files - i will update this once i test that
UPDATE TO USING VS MVC Basic Template: Same error resulted - still no solution
ANOTHER PERSON EXPERIENCING THE SAME PROBLEM
Right here is another stackoverflow question that mimics mine - however I tried his solution to no avail - maybe someone else who is having this same problem can benefit from the link
UPDATE
I recently just tried putting this into MS Sql Server and the view scaffolding adds fine with no error - so I'm not sure if its my MySql database or connection string or what... driving me nuts..
Other References
It appears someone else is having the same issues I am - the only difference is they are using sql server - I tried tweaking all my code to follow the suggestions on this stackoverflow question/answer here but still to no avail
POSSIBLE FIX???
So this is weird... after hooking it up to MS Sql Server and adding the controller, then reverting the connection string to MySql it is actually WORKING with MySql... what the heck!??
So it seems that when you try to add your controller and the view scaffolding (is that the right phrase?) is added WITH the mysql connection string it fails...however if you hook it up to a sql server db, generate the scaffolding/controller, then revert to mysql connection string it works.... ?!?!
It seems that MVC4 Controller scaffolding is not properly recognizing MySql Connection String. Change the connection string as shown below when generating EF CRUD code for Controllers:
<connectionStrings>
<add name="BTDContext" connectionString="Data Source=host_name;Database=database_name;uid=user_id;pwd=password;" providerName="System.Data.SqlClient" />
</connectionStrings>
Change it back to standard when running the application:
<connectionStrings>
<add name="BTDContext" connectionString="Data Source=host_name;Database=database_name;uid=user_id;pwd=password;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
Note the change, provider name.
The imesh suggesting almost solve my problem, but additionally I temporary commented line
[DbConfigurationType(typeof(MySqlEFConfiguration))]
which was in DBContext class. And of course after creation controller this line should be uncommented and change back System.Data.SqlClient to MySql.Data.MySqlClient in config file.
Using VS 2013, MySQL Connector/NET 6.9.6, Entity Framework 6, Web API 2.2 and MySQL server 5.7 I had to combine the answers to prevent the error about "Unable to retrieve metadata".
To successfully add a controller to a .NET project that uses a MySQL connection, do the following:
Temporarily add a connection string with System.Data.SqlClient as the providerName, and comment the one for MySQL. It doesn't matter whether the connection string is valid.
Ensure that MySqlEFConfiguration isn't enabled in any way.
Rebuild.
About the second point, the MySQL documentation on using Connector/NET with EF6 states three possible ways to enable the MySqlEFConfiguration. Ensure that none of these are enabled while adding controllers using the VS template.
Adding the DbConfigurationTypeAttribute on the context class:
[DbConfigurationType(typeof(MySqlEFConfiguration))]
Calling DbConfiguration.SetConfiguration(new MySqlEFConfiguration())
at the application startup
Set the DbConfiguration type in the configuration file:
<entityFramework
codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration,
MySql.Data.Entity.EF6">
I tested also around this bug and saw an other problem.
Following code is in my Web.config (without, it don't work):
<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
Changed it to:
<entityFramework>
Works for me... add the scaffolding and then change it back
I've been having the same problem using EF 4.3.1 and MySql Connecter/Net 6.6.4.0
This worked for me, no need to connect to a different db or extra code in the Context class.
Add this between the entityFramework tags in your web.config file when you want to build a scaffold:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
Then comment the above code out when you want to run migrations and vice versa.
So you web.config will look like so:
<entityFramework>
<contexts>
<context type="ApptManager.Models.AppointmentsManagerContext, ApptManager">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[ApptManager.Models.AppointmentsManagerContext, ApptManager], [ApptManager.Migrations.Configuration, ApptManager]], EntityFramework" />
</context>
</contexts>
<!--<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>-->
</entityFramework>
This is quite ridiculous how .NET developers have to jump through some arduous hoops in order to get their code working.
Working example
https://github.com/dublinan/mvc-mysql-ef-example
Links to my github project
Please try using the
System.ComponentModel.DataAnnotations
namespace along with the [Key] attribute on the EDM class members.
It worked for me.

Resources