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

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

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.

"Object reference not set to an instance of an object" when creating a new Web API controller with EF Scaffolding in Visual Studio 2012

I have an MVC4/Web API project, with an Entity Framework, Code First data model. When I try to create a new API Controller with read/write methods using a data context & model, I get an alert saying "Object reference not set to an instance of an object".
I've done a bit of searching and found that some causes are incorrect project type Guids in the .csproj file, incomplete installation of the MvcScaffolding nuget package and one suggestion of installing Powershell 3.
I have made sure all my project type guids are correct, made sure the MvcScaffolding package is installed correctly, and I've even installed Powershell 3.
None of this has solved the problem for me. All I can think is there is a problem with my data context/model although it created the tables/relationships fine. Code below:
Context:
public class PropertySearchContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Property>().HasRequired(p => p.Office).WithMany(o => o.Properties).HasForeignKey(p => p.OfficeId);
}
public DbSet<Office> Offices { get; set; }
public DbSet<Property> Properties { get; set; }
}
Model:
[Serializable]
public class Property
{
public int PropertyId { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public int Bedrooms { get; set; }
public int Bathrooms { get; set; }
public string UmbracoNodeId { get; set; }
public string MainImageUrl { get; set; }
public string ListingImageUrl { get; set; }
public int TotalImageCount { get; set; }
public PropertyType PropertyType { get; set; }
public PropertyStatus PropertyStatus { get; set; }
public long Price { get; set; }
public string ListingUrl { get; set; }
//Navigation Properties
public int OfficeId { get; set; }
public virtual Office Office { get; set; }
//Meta properties
public DateTime CreatedAt { get; set; }
public string CreatedBy { get; set; }
public DateTime UpdatedAt { get; set; }
public string UpdatedBy { get; set; }
}
Connection String:
<add name="PropertySearchContext" connectionString="Data Source=MERCURY\SQLEXPRESS;Initial Catalog=DATABASE_NAME;Integrated Security=False;User ID=dbFakeUser;Password=fakePassword;Connect Timeout=10" providerName="System.Data.SqlClient" />
Any help with this would be greatly appreciated as I've tried every suggestion and I still can't create a controller with scaffolding. Driving me mad!
Thanks!
Found the problem. In my model, I had a property with a custom enum type, which was in my business project. In my service project, I had my data model project referenced but not the business project. So adding a reference to the model AND business project allowed me to add scaffold controllers fine.
Seems obvious I know, but the error message it gives you is so unhelpful!
Anyway, I hope this helps anyone having the same problem, and can't fix it using the other suggestions.
I am adding an answer as my problem was the same and my solution was different. It had no relation to the referenced assemblies. First of all, I believe it only happened because the Web API project had just been created (from scratch).
I will give you some code examples based on the OP code. First, my context class that inherits from DbContext had to call the base constructor passing as argument the connection string name:
public class PropertySearchContext : DbContext
{
public PropertySearchContext () : base("name=PropertySearchContext")
Second, the Web API application would internally look inside Web.config for a connection string named PropertySearchContext. Web.config already comes with a DefaultConnection, so I just had to add a new one with the proper name and settings:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DATABASE_NAME.mdf;Initial Catalog=DATABASE_NAME;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="PropertySearchContext" connectionString="Data Source=MERCURY\SQLEXPRESS;Initial Catalog=DATABASE_NAME;Integrated Security=False;User ID=dbFakeUser;Password=fakePassword;Connect Timeout=10" providerName="System.Data.SqlClient" />
</connectionStrings>
note: the OQ already has that connection string.
Third and finally, I had to build the WebAPI project. Once successful, the creation of controllers worked fine.
I get this error if I am attempting to Scaffold a controller with views for a Model that does not contain a default constructor(one that does not need parameters). Add one to the model and try again. This has bitten me more than once.
The newer compilers works just fine without one, as if it does not see one it just inserts one for you. However the scaffold operation needs that default constructor be actually declared in code to operate correctly. I just wish it gave you a better explanation when you get the error.
So for the original post simply adding this to the class :
public Property(){}
should do the trick.
If you have more than one project in your solution try to rebuild all.
This answer depends on many things. On my case I didn't have a problem with the model itself. After long hours looking I discovered that another project, which was being referenced on my MVC .NET website, was the one stopping the scaffolding from running correctly.
What I am doing (kind of tedious) is to remove the reference (breaks many things meanwhile), Add the controllers/views that I need, then add the reference again and voila. No "Object Reference" error.
Hope this works for you

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.

Schema not being created when using Entity Framework 4.1 and Code First?

I am running tests against my context and thought EF 4.1 was supposed to create the schema for me in my database, it is not though. I am getting an error that db.Users does not exist in my database, but it is because it is not being created.
public class MyContext: DbContext
{
DbSet<Address> Addresses { get; set; }
DbSet<Region> Regions { get; set; }
DbSet<Country> Countries { get; set; }
DbSet<Contact> Contacts { get; set; }
DbSet<User> Users { get; set; }
}
Here is my db connection string:
<add name="MyContext" connectionString="Data Source=DIW-7-1;Initial Catalog=TestDb;Integrated Security=True" providerName="System.Data.SqlClient" />
I already had a database created without tables so the default initializer was not dropping my database to create the tables. Thanks to Ladislav Mrnka for the help, again!

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