Entity Framework Not Showing Database - asp.net

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);
...
}

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")
{
}
}

How to format XML in POST body for an asp.net WebAPI POST route

I have an asp.net WebAPI RESTful service, where I have a POST endpoint for GPS positions.
The server controller has the following route:
public HttpResponseMessage PostGpsPositions(GpsPositionsModel positions)
The body classes are as follows:
public class GpsPositionsModel
{
[Required]
public int SenderId { get; set; }
[Required]
public List<GPSData> Positions { get; set; }
}
public class GPSData
{
[Required]
public double X { get; set; }
[Required]
public double Y { get; set; }
[Required]
public double Z { get; set; }
}
I always just use json, but someone has asked me if they can submit the body in XML.
It appears this should be possible, by including the Content-Type:"application/xml" header.
I would have thought the format would look like the following:
<?xml version="1.0"?>
<GpsPositionsModel>
<SenderId>1</SenderId>
<Positions>
<GPSData>
<x>1.1</x>
<y>1.1</y>
<z>1.1</z>
</GPSData>
</Positions>
</GpsPositionsModel>
But this just did not work, I get back 400 Bad Request.
I have a validating filter on the server:
ValidationFilterAttribute : ActionFilterAttribute
and in the OnActionExecuting I can see it does have the XML content header, but the model state is false:
So, my question is how should the XML be formatted here? Do I need ArrayOf somewhere in the structure, and if so how do I apply this to the list I am sending?
Update
Added attributes as suggested in comments.
So server side I have:
namespace Models.Common
{
[DataContract(Namespace = "http://mynamespace.com")]
public class GpsPositionsModel
{
[DataMember]
[Required]
public int SenderId { get; set; }
[DataMember]
[Required]
public List<GPSData> Positions { get; set; }
}
[DataContract(Namespace = "http://mynamespace.com")]
public class GPSData
{
[DataMember]
[Required]
public double X { get; set; }
[DataMember]
[Required]
public double Y { get; set; }
[DataMember]
[Required]
public double Z { get; set; }
}
}
Controller:
[HttpPost]
[Route("gps")]
public HttpResponseMessage SubmitGpsData([FromBody]GpsPositionsModel gpsData)
{
return new HttpResponseMessage();
}
And using Postman, I call using:
<?xml version="1.0"?>
<GpsPositionsModel xmlns="http://schemas.datacontract.org/2004/07/http://mynamespace.com">
<SenderId>1</SenderId>
<Positions>
<GPSData xmlns="http://schemas.datacontract.org/2004/07/http://mynamespace.com">
<x>1.1</x>
<y>1.1</y>
<z>1.1</z>
</GPSData>
<GPSData xmlns="http://schemas.datacontract.org/2004/07/http://mynamespace.com">
<x>1.1</x>
<y>1.1</y>
<z>1.1</z>
</GPSData>
</Positions>
</GpsPositionsModel>
And in Postman console I get:
I am using WebAPI2, asp.net full framework
<package id="Microsoft.AspNet.Cors" version="5.2.4" targetFramework="net47" />
<package id="Microsoft.AspNet.WebApi" version="5.2.4" targetFramework="net47" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.4" targetFramework="net47" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.4" targetFramework="net47" />
<package id="Microsoft.AspNet.WebApi.Cors" version="5.2.4" targetFramework="net47" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.2.4" targetFramework="net47" />
<package id="Microsoft.AspNet.WebApi.Tracing" version="5.2.4" targetFramework="net47" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.4" targetFramework="net47" />
For posting xml you need to specify the xmlns in the format:
http://schemas.datacontract.org/2004/07/Clr.Namespace
So in your case you need to post xml like this:
<GpsPositionsModel xmlns="http://schemas.datacontract.org/2004/07/{namespance containing GpsPositionsModel class}">
<Positions>
<GPSData>
<X>1</X>
<Y>1</Y>
<Z>2</Z>
</GPSData>
</Positions>
<SenderId>1</SenderId>
</GpsPositionsModel>
In case the GpsPositionsModel class in not inside any namespace you can leave it empty like:
xmlns="http://schemas.datacontract.org/2004/07/
Reference: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/data-contract-names
Try adding [FromBody] attribute to the parameter in the action method
public HttpResponseMessage PostGpsPositions([FromBody]GpsPositionsModel positions)
Also, to the model
add [DataContract] over the class name and [DataMember] over each of the properties in the model

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();

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.

Resources