Code First Entity Framework not building database - c#

I am trying to implement Entity Framework using code first but it is not building the database tables. I'm not sure what i'm doing wrong. I am using this tutorial -http://msdn.microsoft.com/en-us/data/jj193542 but I am trying to use it with a web application instead of a console application. I created a Models folder and put my context class in that folder. Here is my dbcontext code:
namespace GroceryAssistant.Model
{
public class GroceryShopperContext : DbContext
{
public DbSet<List> Lists { get; set; }
public DbSet<ListItem> ListItems { get; set; }
public DbSet<User> User { get; set; }
}
}
I created put the connection string in the web.release.config and the web.debug.config files. I'm not sure what else I have to do. Where should i put my DbContext code so that the tables will be created?

If you do not change the default behavior, the first time you use the DbContext it will create your database.

Related

Consuming View in EF Code First conflicts with migration

I have a Table "IncomingChecks" in my database. I've created it using EF Code first. Now, I've added a view to my database based on this table named "ViewIncomingChecks" using Sql Server Management Studio and I want to use its data in my app using Entity Framework.
I copied the model class and changed its name and added it to the context:
public class ViewIncomingCheck
{
[Key]
public int Id { get; set; }
//...
}
public class CheckDataContext : DbContext
{
public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks { get; set; }
//...
}
now when I run the app, it throws an exception saying the DB Context has been changed and needs a migration. I even tried to add a migration (which seems to be the wrong option) and when I add the migration, it says that the object ViewIncomingChecks is already in the database.
How can I use this view in my code?
Edit
My current solution is to have another context just for the views. This way it doesn't conflict with the EF Migrations. Is this the best option or is there a better way to deal with it.
According to what I have done in my project:
First add public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks
{ get; set; } to your DbConext
Now create a migration something called ViewDbSetAdded
Remove all the code from the both Up and Down method and it will look like as follows:
Migration Code:
public partial class ViewDbSetAdded : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
Now run update-database command and it will run an empty migration.

Entity Framework 7 Update DbContext after migration

I've got an existing DB and new WPF project.
1) I scaffolded db context with Scaffold-DbContext and recieved DbContext.cs and a file for each entity that represents a DB tables. That's OK.
Here is example of one of them:
public partial class SomeEntity
{
public long SomeEntityID { get; set; }
public int SomeInt { get; set; }
}
2) I've manually updated this entity (no changes in DbContext.cs) :
public partial class SomeEntity
{
public long SomeEntityID { get; set; }
public int SomeInt { get; set; }
public string SomeString { get; set; }
}
3) I've used Add-Migration command. Now I've got a migration file that describes required changes and DbContextSnapshot.cs. Snapshot includes changes I've just made with SomeEntity. Database is not updated.
4) I've used Update-Database command. Database updated to match last migration. But my DbContext.cs doesn't know anything about changes in DB. It is still the same old good DbContext that I had after scaffolding DB.
Is this OK? Should I now change DbContext manually to match changes that I've made to my entities and applied them to DB? Is there a way to update DbContext.cs from DB after changes without 'rescaffolding'? (Because, for example, all comments and attributes in entity files will be lost, because they will be replaced with new ones if I use Scaffold-DbContext again)
You will have to run scaffolding again, but keep in mind that the generated classes are partial, so you can put your changes in another file

Assigning foreign key to my primary key

I am just a learner when it comes to asp.net and I am currently learning mvc5 as I have vs2013 installed in my system.
The questions I have goes this way:
I want to code a simple application to quicken my learning in asp.net programming. What I'm currently coding that is so problematic to me, as a new asp.net and c# programmer, is I can't add a profile to the apps.
I opened a new asp.net mvc apps and some folder was automatically created for me. Now you will agree with me that, only username, email and password are required of you to register for the new app. I want to add a profile page to the same database that Microsoft created by default but I don't know how to add it. I created a profile class file in my model folder but I don't even know how to set a foreign key in case I want to use some particular entity from other class...
My code is shown below... please how do I add this to the default database and to assign the key as the foreign key?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebCHECKING.Models
{
public class Profile
{
public int ProfileID { get; set; }
public string Firstname { get; set; }
public string Secondname { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Picture { get; set; }
public string Facebook { get; set; }
public string Description { get; set; }
public DateTime Datejoined { get; set; }
}
}
As opposed to creating a new class to store the profile info you could expand the existing AplicationUser class with these new fields. Check out this article. The article is actually referenced in your project (open IdentityModels.cs). If you go with this approach you may want to make the additional fields optional so that the user doesn't have to fill everything out as they register.
If you're set on using a seperate class for profile data, add using Microsoft.AspNet.Identity; to your model and reference the ApplicationUser like: public virtual ApplicationUser UserPerson {get; set; }. Check out this SO question for details regarding setting the value of the field in your controller.
-Edit-
Sorry, didn't see your first question about the DB. If you're using Entity Framework, you can add a controller for this model and select the MVC 5 Controller with views, using Entity Framework option. This way, EF will add a database context for you and scaffold a bunch of views and controller actions. If you'd rather not scaffold everything like that you can open up IdentityModels.cs and under the public static ApplicationDbContext Create() method, add a DbSet statement like public System.Data.Entity.DbSet<WebCHECKING.Models.Profile> Profiles {get; set; }. You'll have to run a database migration as well to create the tables.
-One more edit-
If you need to reference another class (other than ApplicationUser), simply substitute the data type for the name of the class like: public profileStuff stuff {get; set; }. EF will add a column to your database table for that class specifying an Id to the class you're referencing it in. This series of "getting started" videos might be pretty helpful in this context.

ASP.NET Identity - Multiple object sets per type are not supported

I got an error using ASP.NET Identity in my app.
Multiple object sets per type are not supported. The object sets
'Identity Users' and 'Users' can both contain instances of type
'Recommendation Platform.Models.ApplicationUser'.
I saw a few questions about this error in StackOverflow. All indicate on two DbSet objects of the same type. But in my DbContext there aren't the same types of DbSets. Exception is thrown on FindAsync() method during logging in.
if (ModelState.IsValid)
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null && user.IsConfirmed)
{
The problem is I don't have two DbSets of the same type. My Contexts look like this:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public System.Data.Entity.DbSet<RecommendationPlatform.Models.ApplicationUser> IdentityUsers { get; set; }
}
and
public class RecContext : DbContext
{
public RecContext()
: base("RecConnection")
{
Database.SetInitializer<RecContext>(new DropCreateDatabaseIfModelChanges<RecContext>());
}
public DbSet<Recommendation> Recommendations { get; set; }
public DbSet<Geolocation> Geolocations { get; set; }
public DbSet<Faq> Faqs { get; set; }
public DbSet<IndexText> IndexTexts { get; set; }
}
What could cause this problem? Maybe something connected with in-built ASP.NET Identity functionalities? Anyway, what is Users type? I don't have it in my app...
You do have two DbSets` of the same type.
IdentityDbContext<T> itself contains Users property declared as:
public DbSet<T> Users { get; set; }
You're declaring second one in your class.
review this file "ApplicationDbContext.cs", remove the line, generated automatically by scaffold last, should be like this:
public System.Data.Entity.DbSet<Manager.Models.ApplicationUser> IdentityUsers { get; set; }
This issue can arise from using scaffolding to create a View. You probably did something like this: View > Add > New Scaffold Item... > MVC 5 View > [Model class: ApplicationUser].
The scaffolding wizard added a new line of code in your ApplicationDbContext class.
public System.Data.Entity.DbSet<RecommendationPlatform.Models.ApplicationUser> IdentityUsers { get; set; }
Now you have two DbSet properties of the same type which not only causes an exeptions to be thrown in the FindAsync() method but also when you try to use code-first migrations.
Be very careful when using scaffolding or even better don't use it.
Comment the new generated Dbset from identity model class like below
// public System.Data.Entity.DbSet<SurveyTool.Models.ApplicationUser> ApplicationUsers { get; set; }
Whenever I see this problem, I always double check the DbSet. - ESPECIALLY if you are using another language for Visual Studio.
For us who use other language on VS, always double check because the program doesn´t create controllers or models with the exact name. perhaps this should be a thread.. or there is one already and I missed it.

Set up database creation/migrations from code for Entity Framework 6 + MySQL

I've previously used NHibernate and Fluent Migrator in projects to create a database (if it didn't already exist) and update the schema through migration scripts. I'm looking over Entity Framework (6) to do a comparison and I'm having trouble replicating that functionality.
In my App.config, I've set up my connection string and db providers. I then went ahead and created a data model that I would like to be represented as a table in the database.
namespace DataModels
{
public class StoreClient
{
public int Id;
public string DisplayName;
public StoreClient()
{
}
}
}
I then went ahead and created a database context.
namespace DataModels
{
public class StoreContext : DbContext
{
public DbSet<StoreClient> StoreClients { get; set; }
}
}
On service start I created an instance of StoreContext and tried to add and call db.SaveChanges();, but this is failing because there is no schema that matches my StoreClient.
My question is simple. How do I configure my StoreContext (or EF in general) to automatically create my database schema, and how do I set it up to migrate when I make changes to that schema?
This seems simple, but my searching around hasn't gotten me anything that looks remotely familiar coming from the NHibernate world.
If you want your db to be created automatically try to put some code in your Application_Start() method.
for example:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<StoreContext, Configuration>());
StoreContext context = new StoreContext();
context.Database.Initialize(true);
Where Configuration class is created upon automatic migrations are enables in the console. Check out this msdn demo.
Also i am not shure that your code firs model will work that way. If not try changing your fields with properties.
namespace DataModels
{
public class StoreClient
{
public int Id { get; set; }
public string DisplayName { get; set; }
public StoreClient()
{
}
}
}

Categories