EF Code First CTP 5 and SQL SErver 2008 R2 - entity-framework

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

Related

Entity Framework is not creating the database

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.

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>

No tables are created after setting WillCascadeOnDelete on true

We are making a project in ASP MVC4, and are using code-first. This means that our database is automaticly created from our code after running it. But i noticed that optional relationships in the database dont have cascade on delete turned on by default.
So after googling, i found that you had to add it in your context, but this gives me errors.
After I set WillCascadeOnDelete on true and delete my database so the Entity Framework can create it again, it creates the database with no tables in. But if i put it on false, it works without any problems.
Here is the code i use to put it on true:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Location>()
.HasOptional(r => r.PartOfLocations)
.WithMany()
.WillCascadeOnDelete();
base.OnModelCreating(modelBuilder);
}
Here is my location model:
public class Location
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int LocationId { get; set; }
[Display(Name = "Name"), Required]
public String Name { get; set; }
[Display(Name = "Description", ResourceType = typeof(ViewRes.ClassModelStrings))]
public String Description { get; set; }
public int LocationTypeId { get; set; }
[ForeignKey("LocationTypeId")]
public virtual LocationType LocationType { get; set; }
public virtual ICollection<Location> PartOfLocations { get; set; }
public override string ToString()
{
return this.Name;
}
}
Also, if i delete the database to quick after it was created, it gives an error: The database XXX is not accessible.
And it adds " ( single user ) " after the database name, no idea if this helps

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

Must pass connection string to EF 5 DbContext code first else Command Exception

I m just using EF 5.0 and I've recreated a very simple DbContext that was working as is with EF 4.1.
Here context and model
public class AgenciesDatabaseContext : DbContext
{
public DbSet<Agency> Agencies { get; set; }
}
[Table("QryAgency")]
public class Agency
{
[Key]
public string CardCode { get; set; }
public string DisplayName { get; set; }
public string CardFName { get; set; }
public string Address { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
}
I set in global.asax initializer for this context as null because the table already exists
Database.SetInitializer<ExtranetCentralizerContext>(null);
Here's the connection string in web.config :
<add name="AgenciesDatabase" providerName="System.Data.SqlClient" connectionString="..."/>
When I try to use the DbContext in the repository I get this error :
InnerException = {"Invalid column name '...'.\r\n Invalid column name '...'.\r\nInvalid column name '...'."}
It's strange because I could see that there is not connection made to my database.
What I don't understand is that I can make it work if I pass the connection string to the context like this :
public class AgenciesDatabaseContext : DbContext
{
public DbSet<Agency> Agencies { get; set; }
public AgenciesDatabaseContext ()
: base("AgenciesDatabase")
{
}
}
There everything work fine. So my question is : isn't EF suposed to use the connection string that matches it's name (in this case AgenciesDatabase) ??? What makes it fail in this case ?
in your app.config the name should be AgenciesDatabaseContext, not only AgenciesDatabase.