Create database with Entity Framework - c#

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

Related

Cannot generate a new controller via scoffolding in Entity/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" />

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?

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.

How can I have access in membership tables in mvc4?

I am trying to use register and login form in MVC4 . I have used Entity Framework from DB to create the model and now I want to generate the membership tables, but I have tried many things and I still can't access them.
I have 2 connection strings :
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Projekti-20160917211151;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-Projekti-20160917211151.mdf" providerName="System.Data.SqlClient" />
<add name="UniversitetiEntities" connectionString="metadata=res://*/Models.Universiteti.csdl|res://*/Models.Universiteti.ssdl|res://*/Models.Universiteti.msl;provider=System.Data.SqlClient;provider connection string="data source=ARBERS-PC\BERSANTA;initial catalog=Universiteti;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings>
In Account Model I changed the base in UniversitetiEntities :
public class UsersContext : DbContext
{
public UsersContext()
: base("UniversitetiEntities")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
I Also did this chang in InitializeSimpleMembershipAttribute file:
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("UniversitetiEntities", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
but it always throws this exception : The ASP.NET Simple Membership database could not be initialized.
AFAIK, SimpleMembershipProvider user profile management only works with SQL Server database connection string, not an EF connection string.
First, try setting your DB connection string instead of EF-generated connection string as stated here:
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
// also set your DB connection string on current DB context
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
If the first solution won't work, try removing AttachDbFileName property from SQL Server connection string:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Projekti-20160917211151;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
NB: If your DB connection has certain user ID & password to get access, include them in DefaultConnection.
Depending on your EF model generation (code first, database first or model first approach), you can set autoCreateTables: by true or false based from existence of UserProfile table.
Further information: SimpleMembership Provider Reference

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" />

Categories

Resources