Entity Framework is not creating the database - entity-framework

I am trying to create a code first database creation. I have 2 connection strings:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=DESKTOP-1111\SERVER_2014; database=the_userdb;user=sa; password=myPassword" providerName="System.Data.SqlClient" />
<add name="PmisDatabaseContext" connectionString="Data Source=DESKTOP-1111\SERVER_2014; database=the_database;user=sa; password=myPassword" providerName="System.Data.SqlClient" />
</connectionStrings>
At first, I was able to add a migration using this:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsActivated { get; set; }
public DateTime EnrollDate { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{ }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//AspNetUsers -> User
modelBuilder.Entity<ApplicationUser>()
.ToTable("User");
//AspNetRoles -> Role
modelBuilder.Entity<IdentityRole>()
.ToTable("Role");
//AspNetUserRoles -> UserRole
modelBuilder.Entity<IdentityUserRole>()
.ToTable("UserRole");
//AspNetUserClaims -> UserClaim
modelBuilder.Entity<IdentityUserClaim>()
.ToTable("UserClaim");
//AspNetUserLogins -> UserLogin
modelBuilder.Entity<IdentityUserLogin>()
.ToTable("UserLogin");
}
}
then I 'enabled migrations' then 'add-migration InitialDatabase' then 'update-database' and was able to successfully created a new database with the tables for logging in.
Now I want to create a new database with a table named ImageLibraries so I did this in my model:
[Table("ImageLibrary")]
public class ImageLibrary
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id { get; set; }
[Required]
public string UserId { get; set; }
}
then added:
public class PmisDatabaseContext : DbContext
{
public PmisDatabaseContext()
: base("name=PmisDatabaseContext")
{
Database.SetInitializer<PmisDatabaseContext>(new CreateDatabaseIfNotExists<PmisDatabaseContext>());
}
public virtual DbSet<ImageLibrary> ImageLibraries { get; set; }
}
When I try to 'add-migration AddedImageLibrary', in my migrations folder, I get the 'up()' and 'down()' without anything in it. It's not creating the new database and table. Can you please show me how to do this right. Thank you.

Related

How to use auto increment id with Entitiy Framework 6 and PostgreSQL not EF CORE?

I have MVC Framework Project with EF6 and POSTGRESQL. I'm using database first and create edmx file from database.
public partial class MinimalEarthEntities : DbContext
{
public MinimalEarthEntities()
: base("name=MinimalEarthEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<User> User { get; set; }
}
public partial class User
{
public long Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public string GSM { get; set; }
public string Password { get; set; }
}
These code was generated from EF6. ID column is auto increment value. But EF6 can not be instert data due to auto increment not working.
Is there anybody help to solve this problem?

EF Code First, not generating database

I have an console application project in visual 2012. I want to use Entity Framework 6 code-first. when I run my project it does not create any database in my SQL Server. I am not able to create database by code first in my SQL Server.I am not getting any exception while build & run.
below is my code :
namespace CodeFirstNewDBeSample
{
class Program
{
static void Main(string[] args)
{
using (var db = new BlogContext())
{
//Console.Write("Enter a name for new Blog:");
//var name = Console.ReadLine();
//var blog = new Blog { Name = name };
//db.Blogs.Add(blog);
//db.SaveChanges();
}
}
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public virtual IEnumerable<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
public class BlogContext : DbContext
{
public BlogContext() : base("name=BlogDBString") { }
DbSet<Blog> Blogs { get; set; }
DbSet<Post> Posts { get; set; }
}
}
Config File :
<connectionStrings>
<add name="BlogDBString" connectionString="data source=MY-PC;initial catalog=BlogDB;integrated security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

Code first is keep creating a database with the fully qualified name of my context

This is my context class
public class HospitalContext : DbContext
{
public DbSet<Patient> Patients { get; set; }
public DbSet<Doctor> Doctors { get; set; }
public DbSet<Appointment> Appointments { get; set; }
public DbSet<Schedule> Schedule { get; set; }
}
And my connection string
<add name="DbContext"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;
Initial Catalog=HospitalProject;
Integrated Security=True;" />
I'd like to know why when I run the application, the database name is
HospitalProject.Models.HospitalContext
instead of HospitalProject.
Thanks for helping
Try renaming connection string to HospitalContext instead of DbContext

producing .sdf file using DBContext class?

I am follwoing this tutorial from
http://www.asp.net/entity-framework/tutorials/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
No I have created this code:
using MvcApp2.Models;
using System.Data.Entity.Design.PluralizationServices;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MvcApp2.Models
{
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
and in my Web.config I have added this Connection string:
<add name="StudentContext" connectionString="Data Source=|DataDirectory|Student.sdf" providerName="System.Data.SqlServerCe.4.0"/>
When I build my project,according to the tutorial, I should be expecting an SDF file in my appcode callded students

EF Code First CTP 5 and SQL SErver 2008 R2

I can't seem to get the EF Code First to work with SQL Server 2008 R2. The error I am getting is "Invalid object name 'dbo.Movies'."
It is not creating the table automatically.
My connection string:
<add name="MovieDBContext"
connectionString="Server=(local); Database=Movies; Trusted_Connection=true; Integrated Security=True"
providerName="System.Data.SqlClient" />
My model and context class:
public class Movie
{
public int ID { get; set; }
[Required(ErrorMessage = "Title is required")]
public string Title { get; set; }
[Required(ErrorMessage = "Date is required")]
public DateTime ReleaseDate { get; set; }
[Required(ErrorMessage = "Genre must be specified")]
public string Genre { get; set; }
[Required(ErrorMessage = "Price Required")]
[Range(1, 100, ErrorMessage = "Price must be between $1 and $100")]
public decimal Price { get; set; }
[StringLength(5)]
public string Rating { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Movie>().Property(p => p.Price).HasPrecision(18, 2);
}
}
Any help would be much appreciated.
I forget if it's enabled by default but try setting this in your Application_Start (pretty sure it's not)
System.Data.Entity.Database.DbDatabase.SetInitializer<MovieDBContext>(new CreateDatabaseIfNotExists<MovieDBContext>());
Heres my current setup (replace caps with your details):
<connectionStrings>
<add name="TITLEContext" connectionString="metadata=res://*/Models.TITLE.csdl|res://*/Models.TITLE.ssdl|res://*/Models.TITLE.msl;provider=System.Data.SqlClient;provider connection string="Data Source=DATASOURCE;Initial Catalog=DATABASE;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
And then I followed up with this in the Public TITLEContext()
DbDatabase.SetInitializer(new DropCreateDatabaseIfModelChanges<TITLEContext>());
Took a couple tries, but put a break point on one of your loads and check the context's entities. It should have an optiont o see the database connection string...
good luck!
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
hope it helps