Prevent Entity Framework recreating databases but use existing databases instead - c#

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.

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?

EF Code First approach on relationships

Being new to ASP .NET I've been researching on entity modeling approaches and it seems ORM using Entity Framework following Code First is the best approach for me.
By following this tutorial, I have gotten the impression that, for each entity, you need to create a connectionstring (correct me if I'm wrong) and this fact confuses me when it comes to relational data, as, per this example, the database itself seems to cover just one entity. So how is relational data handled in the EF.
PS: For unification purpose, please use entities Movies, Customers and the relational table named under the proper naming conventions.
You create a connection string per DbContext. Here is the class that defines the DBContext:
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
To add more tables to this context, add more lines like this (for examples, public DbSet<Customer> Customers { get; set; }.
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
public DbSet<Ticket> Tickets { get; set; }
}
Accessing these from a context:
public class TicketController {
private MovieDBContext db = new MovieDBContext ();
public ActionResult Index(int movieId) {
var listOfTickets = db.Tickets.Where(t=>t.MovieId == movieId).ToList();
var parentMovie = db.Movie.Where(m=>m.Id == movieId).Single();
...
}
}
Connection String: Contains initialization information that is passed as a parameter from a data provider to a data source.
You need a new connection string each time you are connecting to something different (You can have two different DBContexts using the same ConnectionString), in this tutorial although the Data Source of both connection strings is the same, the AttachDbFileName is different.
When each DbContext is initialized, it will use one of those connection strings. In this tutorial, the first connection string (Default Connection) is used for membership (user accounts and such) and the other connection string is used for your MovieDBContext, and will contain Movies and other things as you progress in the tutorial.
It's also possible to have them both in the same database.

Detect dbms type in Entity Framework (Oracle or SQL Server)

How can Entity Framework detect if it is created from SQL Server or Oracle by code? Is there any
property or method which returns the source database type?
Entity Framework knows it from connection being used in DbContext (either from connection string, because it has Provider part or from instance itself directly). You can get the "type" from DbContext.Database.Connection. I.e.:
DbContext.Database.Connection.GetType().Name
I can't think of a better way of doing this than getting the DbProviderFactory and checking its type.
If you create a class library solution and install the NUnit and EntityFramework nuget packages you can run the below.
using System.Data.Common;
using System.Data.Entity;
using System.Diagnostics;
using NUnit.Framework;
namespace efProviderChooser
{
public class MyThing
{
public int Id { get; set; }
}
public class MyContext : DbContext
{
public DbSet<MyThing> Things { get; set; }
}
public class Test
{
[Test]
public void CanGetProvider()
{
var context = new MyContext();
var dbProviderFactory = DbProviderFactories
.GetFactory(
context.Database.Connection);
Debug.WriteLine(dbProviderFactory.GetType());
//gives one of
//System.Data.EntityClient.EntityProviderFactory
//System.Data.Odbc.OdbcFactory
//System.Data.OleDb.OleDbFactory
//System.Data.OracleClient.OracleClientFactory
//System.Data.SqlClient.SqlClientFactory
//this list could change!
// here I get SqlClient
Assert.That(dbProviderFactory.GetType().ToString().Contains("SqlClient"));
}
}
}

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