A file activation error occurred When using Entity Framework - c#

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?

Related

SQLite CodeFirst example

I try to run a CodeFirst example for Entity Framwork with SQLite.
The NuGet Package SQLite.CodeFirst is installed and runs without errors
but it doesn´t create a SQLite DB.
This is my code:
using SQLite.CodeFirst;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Text;
namespace EF6SqliteExample
{
class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var model = modelBuilder.Build(Database.Connection);
ISqlGenerator sqlGenerator = new SqliteSqlGenerator();
string sql = sqlGenerator.Generate(model.StoreModel);
}
public DbSet<Person> Persons { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var db = new MyContext())
{
var person = new Person() { Name = "John" };
db.Persons.Add(person);
db.SaveChanges();
}
}
}
}
The Connection-String is:
<connectionStrings>
<add name="MyDB" connectionString="data source=.\MyDB.sqlite" providerName="System.Data.SQLite" />
</connectionStrings>
The DbContext class has a method called .Migrate() which will go through the migrations pipeline and create your database if it does not already exist.
Here's a source: Entity Framework Migrations
What I pointed out in your code is, constructor of class MyContext is missing in your code. Add contructor with base and try again.
public MyContext() : base("MyDB")
{
}
after adding constructor in your class, if the Migrations folder is not available yet in your project, you have to write some command as below:
In your visual studio, go to view -> other windows -> package manager console
To enable migration, run enable-migrations . After executing it, you will find Migrations folder.
now add migration with message for current project, run add-migration InitialCreate
to update Database, run update-database
Refresh/Reconnect you server/db. You will find the db there.

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.

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.

EF6 losing context between design and runtime

I have an EF6 Database-First application that adds to a table. The Model appears to have generated perfectly (T4) and intellisense shows exactly what I'd expect at design-time.
However, at runtime, the exception:
The entity type UsedLoanNumbers is not part of the model for the current context."
occurs on the line that first references the UsedLoanNumbers entity:
using (var context = new NLNEntities())
{
UsedLoanNumbers uln = context.UsedLoanNumbers.Last();
uln.UserID = userID;
uln.AssignedDateTime = DateTime.Now;
uln = context.UsedLoanNumbers.Add(uln);
this.LoanNumber = uln.LoanNumber.ToString();
context.SaveChanges();
}
I do have a second EF context in a separate DLL that does logging... They are named completely different, but are both modifying data in the same database:
What am I doing wrong?
Here's the context code:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NewLoanNumber
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class NLNEntities : DbContext
{
public NLNEntities() : base("name=NLNEntities") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<ErrorLogging> ErrorLoggings { get; set; }
public virtual DbSet<LogEntryPriority> LogEntryPriorities { get; set; }
public virtual DbSet<LogEntryType> LogEntryTypes { get; set; }
public virtual DbSet<ProcessLog> ProcessLogs { get; set; }
public virtual DbSet<UsedLoanNumbers> UsedLoanNumbers { get; set; }
}
}
Connection strings:
name="NLNEntities" connectionString="metadata=res://*/LoggingModel.csdl|res://*/LoggingModel.ssdl|res://*/LoggingModel.msl;provider=System.Data.SqlClient;provider connection string="data source=CSTestLSDW;initial catalog=LoanServicingDW;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
name="LoggingEntities" connectionString="metadata=res://*/LoggingModel.csdl|res://*/LoggingModel.ssdl|res://*/LoggingModel.msl;provider=System.Data.SqlClient;provider connection string="data source=CSTestLSDW;initial catalog=LoanServicingDW;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

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