I created my initial project in Visual Studio and discovered I had used SQL Server after I created my initial migration. I then changed all the connection information to use MYSQL and connected successfully. I created the initial migration again and it created all the ASP security tables. I added a new model and updated the database, but it created an empty migration (just UP/DOWN methods)
I've tried multiple fixes I found here and other sites. I backed out the second migration and retried. I tried forcing the migration again (-f). I dropped the new MYSQL db and deleted the migrations then started over, all with the same result.
Here is my model code:
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace congresssucks_conversion.Models
{
public class BlogPost : DBContext
{
public int Id { get; set; }
public string Title { get; set; }
public string ShortPost { get; set; }
public string Post { get; set; }
public string Tags { get; set; }
public DateTime Updated { get; set; }
}
}
And here is the migration file:
namespace congresssucks_conversion.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class blogpost : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
It completes successfully and no errors in the Terminal Window.
You're combining two separate things, your model class and your database context.
Your BlogPostm class shouldn't inherit DbContext, it should be just a plain C# class.
Then you make a new class that looks something like this:
public class BlogDbContext : DbContext
{
public DbSet<BlogPostm> Posts { get; set; }
}
Now you have a class that can represent a single post, and another class that can represent a database with a table of multiple blog posts. The migration generator is looking for those DbSet<whatever> properties, so you should see real migrations after this change.
There are a lot more ways you can describe what you want Entity Framework to do with your database, so it would be worth reviewing an Entity Framework tutorial.
Try to delete a record of last migration from _MigrationHistory table. Maybe This record had been incorrectly created before added DbSet for the new model object to DbContext class. After this delete, new migration was created with correct Up() and Down() methods.
Related
I have my asp.net MVC project with some models generated from the DB.
Now I want to add some new models "manually" (without being generated from the DB) called "TrainingViewModels" to be used on the views.
The problem is that the models inside TrainingViewModels file are not recognized in any controller/view. Below the content of TrainingViewModels.cs:
namespace FMS.Models
{
public class TrainingAdminViewModel
{
public Training Training { get; set; }
public List<UserTrainings> UserTrainingsList { get; set; }
}
}
If I paste the code above on AccountViewModels.cs file everything work as expected. I don't understand why I can't have it declared on a diferent file.
P.S. - It is not a missing import problem I think
I am a newbie to building website's in asp.net mvc5. I followed some tutorials and build my first website based on a existing database, so that's why i choose for database first approach.
Now I want to create with many to many relationship between the applicationuser object with my resource object.
from db point of view:
AspNetUsers <-> ApplicationUserResources <-> Resource
Which steps do I need to follow when using a database first approach to archive this relationship.
Wesley
You can add any navigation props in your ApplicationUser class as well as in any other EF Entity
public class ApplicationUser : IdentityUser
{
public virtual ICollection<Resource> Resources{ get; set; }
}
public class Resource
{
public virtual ICollection<ApplicationUser > ApplicationUsers { get; set; }
}
This question already has answers here:
How do I singularize my tables in EF Code First?
(3 answers)
Closed 6 years ago.
This has happened twice on the same project. I'm using MVC/VS2015 community and I'm adding 2 classes: hauler and sale.
namespace CarThingy2.Models
{
public class Sale
{
public int ID { get; set; }
public int CoNbr { get; set; }
public int Locn { get; set; }
public int Ticket { get; set; }
public int Haul_Code { get; set; }
}
}
so I go to save - then I add the controller, and everything's good except I change the controller "title" (it was scaffolded as "SalesController") to SaleController. Run the project and it gives me an error about "it can't find dbo.Sales" in the "InnerException". I ended up having to enable-migrations, add-migration addsomethingelse and then finally update-database. TWICE (once for hauler, once for sale)!
Am I doing something wrong that grabs the "pluralized" name? This has happened to me before and I would least like an explanation as to why. The weirdest thing now is that the website will work, but the Tables ARE PLURAL (Haulers and Sales).
So were the tables originally called 'dbo.Sale' and 'dbo.Hauler'?
EF default convention is to use singular entity names and plural table names. You can manually specify the table name in the mapping though.
Note - now that you've added migrations, this will trigger another migration (or just delete the Migrations folder in the project and the dbo._MigrationHistory table in the database if you don't want migrations).
In the DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Hauler>().ToTable("Hauler");
modelBuilder.Entity<Sale>().ToTable("Sale");
}
If you have an existing database with all singular names, you can globally remove the pluralization convention in the above method as well:
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
Or via attribute on the entity:
[Table("Sale")]
public class Sale
{
}
My question is very simple, I am using Entity Framework with asp.net MVC.
I am not sure this question is helpful or not, but I have a doubt.
How entity framework should known, that he has to add migration for which class, why EF will not generate migration for ViewModel class ?
I am just want to know how EF will differentiated between ViewModel.cs class and Model.cs class and add migration only for model.
Thanks in advance.
I think it checks which classes have been added to a DbContext.
using System.Data.Entity;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Infrastructure;
namespace MigrationsDemo
{
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
}
}
Blog will now be considered with the migration. Please see this link for more information on code-first migrations: https://msdn.microsoft.com/en-us/data/jj591621.aspx
There are some places that you can add configuration to Entity Framework, but in its basic form, it iterates the properties on your DbContext class (with a public get), and considers all properties of type IDbSet to be a part of the data model.
The properties do not have to have a set. For example, this is a valid entity definition in DbContext that EF will pick up and generate Migration for:
public IDbSet<MyEntity> MyEntities
{
get { return Set<MyEntity>(); }
}
I know this should be simple, but I was unable to find correct tutorial or explanation on web on this subject. There is a lot of videos and posts about adding new column to an existing table, using code first approach, but I can not find any with step by step explanation on how to add whole new table into existing database.
Which is weird, I was pretty sure that I will find many examples. Maybe my search criteria is bad. So if anybody has any good link or video, please share.
What I'm trying to do is to add table Post into existing Default Database, created by MVC 5 project.
I've made model class first, named it Post and it has a simple definition:
public class Post
{
[Key]
public int PostId { get; set; }
public string PostText { get; set; }
public byte[] ImagePost { get; set; }
public byte[] FilePost { get; set; }
public string TextPost { get; set; }
public string UserId { get; set; }
}
Then I have first doubts. I know I should create DbContext, but if I want to hit an existing database, should I use existing DbContext, already created by default in Web.config file like this:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-StudentBookApp-20150114035149.mdf;Initial Catalog=aspnet-StudentBookApp-20150114035149;Integrated Security=True"
providerName="System.Data.SqlClient" />
Or I should use all new DbContext created for Post class?
Anyhow I've tried it both, but no success. When I created this new context I was doing following in PMC:
Enable-Migrations
Add-Migration "PostMigration"
Update-Database
Usually, or all goes well, but I don't get any new table in database, or I get an error: AspNetUsers already exists, and AspNetUsers is one of auto-created tables that I've changed by adding new columns to it.
Update: My context right now is in seperated class named PostContext and it looks like this:
public class PostContext : DbContext
{
public PostContext() : base("name=PostContext")
{
}
public DbSet<Post> Posts { get; set; }
}
Second try:
Since my first approach didn't gave any result. I've tried doing what's described in this link. Adding mapping to my project:
I've crated new class PostConfiguration for mapping:
public class PostConfiguration : EntityTypeConfiguration<Post>
{
public PostConfiguration() : base()
{
HasKey(p => p.PostId);
ToTable("Post");
HasOptional(p => p.PostText);
ToTable("Post");
HasOptional(p => p.ImagePost);
ToTable("Post");
HasOptional(p => p.TextPost);
ToTable("Post");
HasOptional(p => p.FilePost);
ToTable("Post");
HasRequired(p => p.UserId);
ToTable("Post");
}
}
In the class Post I've added context class too PostContext with modelBuilder variable as they've suggested in listed link above:
public class PostContext : DbContext
{
static PostContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<PostContext>());
}
public DbSet<Post> Posts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties()
.Where(p => p.Name == "Key")
.Configure(p => p.IsKey());
modelBuilder.Configurations.Add(new PostConfiguration());
}
}
I've run all PMC commands again, and still no success, table Post is missing from default database.
What has happened here is that you had existing database tables before Migrations where enabled.
So Entity Framework thinks that ALL your database objects need to created, this could be seen by opening up your PostMigration migration file.
The best way is to trick EF into to doing the initial migration with every before you added the Post table and then do the Posts migration after.
Steps
Comment out the Posts in the DBContext so EF doesn't know about posts
//public DbSet<Post> Posts { get; set; }
Enable Migrations
Enable-Migrations
Add an initial migration with all tables prior to your changes
Add-Migration "InitialBaseline" –IgnoreChanges
Now update the database, this will create a MigrationHistory table so that EF knows what migrations have been run.
Update-Database
Now you can uncomment the line in 1 to "Do your change"
Create a new migration with the addition of Posts
Add-Migration "PostMigration"
Now do an update... and hopefully it should all work.
Update-Database
Now that migrations are all setup and they are baselined future migrations will be easy.
For more information I found this link useful:
http://msdn.microsoft.com/en-us/data/dn579398.aspx
You can resolve that by going to migration folder and delete Post-Migration file, then inside migration folder you will find a file named ApplicationContextModelSnapshot or something like that, then delete modelBuilder.Entity related to your post model.
After that do:
Add-Migration "PostMigration"
Update-Database