Cannot generate a new controller via scoffolding in Entity/C# - c#

I am taking a tutorial on getting started with Entity Framework and C#.
I was following the [tutorial][1] and I am getting an error when I tried to create a new scaffolding item. When I select the Model class, data context class and select the controller name, I get the following error message:
"There was an error running the selected code generator: 'There was an error getting the type 'ContosoUniversity.Models.Student'. Try rebuilding the project."
I did rebuild the project, twice actually, and I keep getting this error message. Can anybody tell me what might be happening?
These are the steps I took to create the new scaffold item:
Right-click the Controllers folder in Solution Explorer, select Add,
and then click New Scaffolded Item.
In the Add Scaffold dialog box, select MVC 5 Controller with views,
using Entity Framework, and then choose Add. In the Add Controller
dialog box, make the following selections, and then choose Add:
Model class: Student (ContosoUniversity.Models). (If you don't see
this option in the drop-down list, build the project and try again.)
Data context class: SchoolContext (ContosoUniversity.DAL).
Controller name: StudentController (not StudentsController).
Leave the default values for the other fields.
This is how I have the code set up in my Student class file, under Models:
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 ICollection<Enrollment> Enrollments { get; set; }
}
}
Finally, this is how I have my connections set up to the localDB that is being used in the tutorial.
> <connectionStrings>
> <add name="SchoolContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial
> Catalog=ContosoUniversity1;Integrated Security=SSPI;"
> providerName="System.Data.SqlClient"/> </connectionStrings>

Change your connection string
From this
<add name="xxx" connectionString="Data Source=xxx;initial catalog=xxx;Persist Security Info=True;User ID=xxxx;Password=xxxx;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
To this
<add name="xxx" connectionString="metadata=res://*/EFMOdel.csdl|res://*/EFMOdel.ssdl|res://*/EFMOdel.msl;provider=System.Data.SqlClient;provider connection string="data source=xxxx;initial catalog=xxxx;persist security info=True;user id=xxxx;password=xxx;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

Related

Create database if not exist

I want to create database if its not exist. I am using sqlite as a database source and Entity Framework. At first I added new model (code first) and set database source as database.db in current directory.
Next, I've added simple class:
class User {
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
And of course database context:
class TestContext : DbContext {
public DbSet<User> Users { get; set; }
public TestContext() :base("TestModel"){
//Create database always, even If exists
Database.SetInitializer<TestContext>(new DropCreateDatabaseAlways<TestContext>());
}
}
I've already had connectionString in app.config:
<connectionStrings>
<add name="TestModel" connectionString="data source="C:\Users\root\Documents\Visual Studio 2015\Projects\dbTEST\dbTEST\bin\Debug\database.db"" providerName="System.Data.SQLite.EF6" />
</connectionStrings>
And for some reason after running this piece of code:
using (var ctx = new TextContext()) {
ctx.Database.Create();
}
I am getting error:
An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll
Additional information: Database 'main' cannot be created because it already exists.
I cant understand what's wrong with this. I dont know where main database comes from. I set database file as database.db. Can you help me with that?
Your constructor dictates that the DB will be dropped and created each time the application starts.
Therefore remove ctx.Database.Create() as this is handled by the framework.

MVC Create Controller with read/write actions and views, using Entity Framework. Error [duplicate]

This question already has answers here:
EntityType has no key defined error
(13 answers)
Closed 5 years ago.
So, i am trying to learn how to use MVC Framework.
I used this link as tutorial to pick this framework up:
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-aspnet-mvc3/cs/adding-a-view
I have problem on creating the controller for my Model which named Movie, I encountered an error which i cannot solve when i have reached step "Accessing your model data from controller (C#)"
Every time i try to create a controller like the instructions told me to i received this error:
enter image description here
I am still newbie here so i don;t really know what to do,
I have tried to change the providerName in Web.config to the same as the 2nd connectionStrings but same error keeps appearing, my Model code looks exactly the same as the link i provided
Movie.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace WebApplication1.Models
{
[Table("Movies")]
public class Movie
{
[Key]
public int movieid { get; set; }
public string movie_title { get; set; }
public DateTime release_date { get; set; }
public string Genre { get; set; }
public decimal ticket_price { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
}
Portion of my Web.config
<connectionStrings>
<add name="MovieDBContext"
connectionString="Data Source=|DataDirectory|Movies.sdf"
providerName="System.Data.SqlClient"/>
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebApplication1-20170909114325.mdf;Initial Catalog=aspnet-WebApplication1-20170909114325;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
The error describes about the Movie entity having no keys defined.
Have you updated the schema of the Movies table as shown in the instruction?

Create database with Entity Framework

Im trying to create a database called Todo with Entity Framework. I want this database to appear in Sql Server Managment after It has been created.
I have the context file:
namespace Domain
{
//Associate the model with the database
//This class then automatically defines a property for each table in the database that I want to work with.
public class EFDbContext : DbContext
{
public EFDbContext() : base("EFDbContext")
{
}
public DbSet<List> Lists { get; set; }
public DbSet<Task> Tasks { get; set; }
}
}
I have my Initilizer:
namespace Domain
{
public class ListRepository : System.Data.Entity.DropCreateDatabaseIfModelChanges<EFDbContext>
{
protected override void Seed(EFDbContext context)
{
var todo = new List<List>
{
new List { Day="MÃ¥nadg" },
new List { Day="Tisdag" },
new List { Day="Onsdag" },
new List { Day="Torsdag" },
new List { Day="Fredag" }
};
todo.ForEach(t => context.Lists.Add(t));
context.SaveChanges();
}
}
}
And here I have my Web.Config:
<connectionStrings>
<add name="EFDbContext" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=Todo;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<contexts>
<context type="todo.domain.EFDbContext, todo">
<databaseInitializer type="todo.domain.ListRepository, todo"></databaseInitializer>
</context>
</contexts>
When I run my application, I Data Connections Is created In Server Explorer as In the picture below:
When I click on this Data Connection, I get the following error message:
When I check In Sql Server Managment, no Database Is listed there.
What am I doing wrong here? Why Is not the dabatabase created?
As you can see, I have a solution called Todo, and In the Todo-solution, I have three projects. I have the DbContext In the Domain-project
From your screenshot, it says login failed for user Bryan in your message. This would mean Bryan is unable to connect
Check the following 3 items
From your Sql Management studio, open the Db, right icons and scroll down to security, (in windows authentication mode, usually easiest) and scroll down to security and then add Bryan as a user giving him DBO rights
Authentication type Check is Mixed Mode authentication is enabled
Switch the connection to Authentication and try with SA role

Entity Framework Code First (New Database) Producing Error - "CREATE DATABASE permission denied in database 'master'."

I have created a new project (ASP.NET MVC) that will use Entity Framework Code First to create a new Database and add records to the database one time only and populate a drop down.
I am trying to figure out how to generate the database automatically. So far, when I run the code I get "CREATE DATABASE permission denied in database 'master'.". Master is not the correct database. What would I need to modify in my code or connection string to create the database automatically from scratch?
Controller:
namespace TDReport.Controllers
{
public class ReportController : Controller
{
//
// GET: /Report/
public ActionResult Index()
{
var db = new StageContext();
if (!db.Database.Exists())
{
db.Database.Create();
db.Stages.Add(new Stage { PCR = 201 });
db.Stages.Add(new Stage { PCR = 202 });
db.Stages.Add(new Stage { PCR = 203 });
db.Stages.Add(new Stage { PCR = 501 });
db.SaveChanges();
}
return View();
}
Context Class:
namespace TDReport.Models
{
public class StageContext : DbContext
{
public DbSet<Stage> Stages { get; set; }
public DbSet<Report> Reports {get; set;}
}
}
Model:
namespace TDReport.Models
{
public class Stage
{
public int ID { get; set; }
public int PCR { get; set; }
}
}
Connection String Tags:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-TDReport-20140825134744;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-TDReport-20140825134744.mdf" />
<add name="StageProductionEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\StageProduction.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
You need to have a connection string that matches the name of db context if you have parameterless constructor in the db context.
<add name="StageContext" providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial
Catalog=TheDatabaseName;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|\TheDatabaseName.mdf" />

Can't get EF Code First to work in MVC 4

I create a new MVC 4 Internet Application in VS 2010. I created an "Item" model, and an "ItemContext" class:
public class Item
{
public int ItemID { get; set; }
public string Name { get; set; }
}
public class ItemContext : DbContext
{
public DbSet<Item> Items { get; set; }
}
I built the project, then right clicked the "Controllers" folder, and attempted to add a new controller:
when I try to add it, I get the following error, which I do not understand:
I'm having bigger issues with this, but I thought I'd try boiling it down as simple as I could and see what I got. What steps am I missing? The "Internet Application" project has a connection string already, and it's got some membership related stuff as well.
Update This is the connection string the project creates:
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnet.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
Change the connection string name to ItemContext.
Here is another way of doing it without need to rename connection. DefaultConnection may be any of yours connections.
public class ItemsContext : DbContext
{
public ItemsContext()
: base("DefaultConnection")
{
}
public DbSet<Item> Items { get; set; }
}
This approach gives you the benefit to avoid having new connection name for each new Model set.

Categories

Resources