Create database if not exist - c#

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.

Related

A file activation error occurred When using Entity Framework

I want to use the Scaffolding Mechanism in the Entity Framework to create a MusicDBContext database and table automatically, but a problem occurred when I was programming.
The creation of steps shown below:
1. Create a console application.
2. Use the NuGet to install the Entity Framework: PM> install-package Entity Framework
3. Insert the following code into the configuration Session in App.Config:
<connectionStrings>
<add name="MusicDBContext"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;
Initial Catalog=MusicDBContext;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\MusicDBContext.mdf"
providerName="System.Data.SqlClient" />
</connectionStrings>
4. Write the following code in the console:
using System;
using System.Linq;
using System.Data.Entity;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
try
{
MusicDbContext db = new MusicDbContext();
Music music = new Music { Title = "Far Away From Home",
ReleaseDate = DateTime.Now };
db.Musics.Add(music);
db.SaveChanges();
db.Musics.ToList().ForEach(x => Console.WriteLine($"{x.ID},
{x.Title},{x.ReleaseDate}"));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
if(ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);
}
}
Console.ReadKey();
}
}
public class Music
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { set; get; }
}
public class MusicDbContext : DbContext
{
public MusicDbContext() : base("MusicDBContext") { }
public DbSet<Music> Musics { set; get; }
}
}
However, the following error occurred during runtime:
A file activation error occurred.
The physical file name '\\MusicDBContext.mdf' may be incorrect.
Diagnose and correct additional errors, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created.
Check related errors.
When I delete all the content in the connectionStrings session, it runs OK.
Entity Framework uses the default connection of SqlLocalDB.
ConnectionString shown below:
Data Source=(localdb)\\mssqllocaldb;Initial Catalog=MusicDBContext;Integrated Security=True;MultipleActiveResultSets=True
Why is there a problem with the connection named MusicDBContext?
The keyword DataDirectory has problem?

Following Entity Framework code-first approach, why is connection string not created? (No DB created)

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

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

Prevent Entity Framework recreating databases but use existing databases instead

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.

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