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.
Related
I have a very basic model class
class Student
{
public int StudentID { get; set; }
public string Ad { get; set; }
public string Soyad { get; set; }
}
and a very basic DbContext class
class StudentContext: DbContext
{
public StudentContext() :base("StudentDB")
{
}
public DbSet<Student> Students { get; set; }
}
I've tried with both a console app and also an ASP.NET MVC 5 project. Neither worked :/
When I build and run the application no database gets created. When I examine, I realized that although I even passed a parameter for DB Name in the base constructor, no connection string is inserted into app.config or web.config.
The Entity Framework Nuget package was installed before each trial and EF worked fine for my previous database first projects. I have no idea why I can't create database at first run. I even tried to add following line in Main() function of console project:
StudentContext ctx = new StudentContext();
ctx.Database.CreateIfNotExists();
Did not work :/
Where does it say that the DbContext(string) would create a connection string in app.config? The remarks section of the DbContext class describes the connection string. But is says nowhere that the DbContext class would adjust app.config.
Changing the app.config would be undesired behaviour. What if you want the same DbContext to control two similar databases, for instance to copy data from one database to the other?
To get the the connection string after creating a DbContext instance use:
dbContext.Database.Connection.ConnectionString;
If you want to write the connection string to the App.Config, I'd suggest you'll write an extension function for it:
static class DbContextExtensions
{
public static void SaveConnectionString (this DbContext dbContext)
{
string connectionString = dbContext.Database.Connection.ConnectionString;
SaveConnectionString(connectionString);
}
private static void SaveConnectionString(string connectionString)
{ // save the string where you want it, for instance app.config
// out of scope of this question
}
}
usage
using(var dbConext = new StudentContext("...");
{
dbContext.SaveConnectionString();
}
Alternate option would be - "Initializer". If you want to create database on application start either use:
context.Database.Initialize(true);
but you can't use when you're using "Initializer"
ctx.Database.CreateIfNotExists();
That solution does not work in .net core 2 tied to SQL Server 2016. Original Question: Trying to jump into entity framework, using the "Code First Approach". I have my new class setup “NewTable” shown below. I can’t figure out what in the Program Manger Console I need to type to get this table created in my Default Connection String (pointing to a local instance of Sql Server 2016). The database is working and the user in this .net core 2 web app can register his/her name then log in using that new created account. Thanks in advance!!
Default Connection String:
"ConnectionStrings": {
"DefaultConnection" "Server=localhost\RCDSE_Dev;Database=Some Database;User ID=sa;Password=SomePass;"
},
[Table("NewTable")]
public class NewTable
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] //Database generated key
[Key] //Primary Key
public long Id { get; set; }
[Required]
public string Manager { get; set; }
}
public class NewTableContext : DbContext
{
public DbSet<NewTable> NewTables{ get; set; }
}
Add a constructor to the DbContext as below:
public class NewTableContext : DbContext
{
public DbSet<NewTable> NewTables{ get; set; }
public NewTableContext() : base("DefaultConnection") { }
}
I figured this out. Will post a detailed step by step guide for others in the next couple of days. There are specific things that need to be done in .net core 2 project file that were NOT COVERED in any of the referenced examples by users here. Thanks for all the help..it got me somewhat pointed in a direction, to find the right direction...lol.
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.
My problem lies in the lack of experience in MVC. Basically, I have two tables in DB
-Person
-Offer
For each I have created a model and a controller and a model, so the structure looks like that:
public class Offer
{
public int OfferID { get; set; }
public string OfferTitle { get; set; }
public string State { get; set; }
public string Description { get; set; }
}
public class OfferDBContext : DbContext
{
public DbSet<Offer> Offers { get; set; }
}
This is the Offer model.
public class Person
{
public int PersonID { get; set; }
public string Username { get; set; }
public DateTime Birthday { get; set; }
public string Education { get; set; }
public string Email { get; set; }
}
public class PersonDBContext : DbContext
{
public DbSet<Person> Persons { get; set; }
}
This is the Person model.
Firstly I created the Person model, that added itself to db without any problems. Then I wanted to add Offer table, and I had to use the DropCreateDatabaseIfModelChanges method. I used it for OfferInitializer and PersonInitializer and then there is the Global.asax.cs file
protected void Application_Start()
{
Database.SetInitializer<OfferDBContext>(new OfferInitializer());
Database.SetInitializer<PersonDBContext>(new PersonInitializer());
//Database.SetInitializer<PersonDBContext>(new PersonInitializer());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
From what I understand, I cant do that simply because I am dropping database 2 times, each time populating only one table at a time. How do I reorganize it all, so that I can populate both or more tables at a time, or the whole database?
First things first, you should not create individual DbContext classes for each table. You should instead put all your DbSets in the same DbContext. Doing this will simplify things greatly for you.
Secondly, you should look into using migrations. You should start using them very early in your project.
You work with code first migrations using the Package Management Console.
enable-migrations
Does exactly what the name implies. Initializes migrations in your project. This will create a folder inside your project and generate the files needed.
add-migration InitialCreate
This creates a migration. InitialCreate is actually a string and you can change it to whatever you want. This command will generate the scripts needed to create the database from strach.
update-database
This command verifies the database and applies the migration (or migrations - there can be multiple) required in order to get the database up-to-date.
This is the initial setup. If you do further changes to your first code first classes, or add more, you will just have to add a new migration and then execute it.
add-migration AddedFirstName
update-database
It's that simple!
There are some more advanced concepts like seed, rollback, update to specific migration, etc., but what I have typed above covers the basics and the day to day usage of migrations.
I recommend you to read this article which explains everything in much more detail: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application
Good Day,
I understand so far that EF tries to have the developer work in a code-first paradigm. I am having trouble with my setup at the moment because EF wants to Create a database - and it is being denied. I have already created a database and also changed the generated database connection string to where I want it to connect - and which database to use.
I haven't extensively used EF in my career, but I see a growing need for it over the ADO.NET approach. I have decided to try my hand at it. Here is what I have:
Connection String
<add name="DefaultConnection" connectionString="Data Source=EON-PC\2008;Initial Catalog=Experimental;Integrated Security=true;" providerName="System.Data.SqlClient" />
MVC Models
namespace EFExperiment.Models
{
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
[Table("stores")]
public class Stores
{
[Key]
public string Id { get; set; }
public string StoreName { get; set; }
public string AdminEmail { get; set; }
public string Url { get; set; }
}
public class StoreDbContext : DbContext
{
public StoreDbContext()
{
//Database.SetInitializer<StoreDbContext>(null); //Tried this - also failed. It didn't try to create a database here
}
public DbSet<Stores> Stores { get; set; }
}
}
Controller
namespace EFExperiment.Controllers
{
using EFExperiment.Models;
using System.Linq;
using System.Web.Mvc;
public class StoresController : Controller
{
private StoreDbContext db = new StoreDbContext();
public ActionResult Index()
{
return View(db.Stores.ToList());
}
}
}
Error:
CREATE DATABASE permission denied in database 'master'.
What confuses me now is - how do you use EF when it is intended to wipe and recreate your DB? Am I missing something here? I would like to read from my actual tables in my DB, along with other CRUD operations - not have it recreate it every time I run my application.