How to add Column in existing table in asp Boilerplate? - asp.net

As you know Boilerplate don't give the entity classes to add columns and I want to add column in table named ( AbpUser). I tried to make a class in Migrations like below
public partial class AddRatingMig : DbMigration
{
public override void Up()
{
AddColumn("dbo.AbpUsers", "UserType", c => c.String());
}
public override void Down()
{
DropColumn("dbo.AbpUsers", "UserType");
}
}
Then in Pm console run command Update-Database
. But not successful. As you know Boilerplate don't give the entity classes to edit columns. Please Help Thanks in advance

The answer to this question is to Extend the AbpUser like this
public class User : AbpUser<User>
{
public string SpecialTitle { get; set; }
}
and add-migration UpdatedUserWithSpecialTitle
then update-database

Here is the correct way
public partial class AddRatingMig : DbMigration
{
public override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "UserType",
table:"AbpUsers",
nullable:true
);
}
public override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name:"UserType",
table:"dbo.AbpUsers"
);
}
}
Hence update Database using code as: update-database
NOTE:
Make sure that you have properly added migrations as:
add-migration migration_name

I had the same problem in abp.io framework, adding new property, "PICUstomerId" to AbpUser Entity and migrate it to database.
Here is the comments by abp.io:
Add your own properties here. Example:
public string MyProperty { get; set; }
If you add a property and using the EF Core, remember these;
Update PasargadInsuranceDbContext.OnModelCreating to configure the mapping for your new property
Update PasargadInsuranceEfCoreEntityExtensionMappings to extend the IdentityUser entity and add your new property to the migration.
Use the Add-Migration to add a new database migration.
Run the .DbMigrator project (or use the Update-Database command) to apply schema change to the database.
and finally add-migration to your solution and then update-database
1. Add your own properties here
2. Update PasargadInsuranceDbContext.OnModelCreating
3. Update PasargadInsuranceEfCoreEntityExtensionMappings to extend theIdentityUser entity
4. And finally after update-databse, I saw my new property in database

Related

No changes in model, should EF migration create empty empty Up() Down() methods? Or no migration at all?

I'm using EntityFrameworkCore Code First to create my SQL migration scripts.
After every change in my model, I run Add-Migration changeInModel and a corresponding XXXXXXXX_changeInModel.cs file is being generated in my Migrations folder.
If I don't make any change in my models AND I run Add-Migration noChangeInModel , I was assuming (out of nowhere) no generation of XXXXXX_noChangeInModel.cs
However, EF Core is creating a XXXXXX_noChangeInModel.cs with an empty Up and Down methods.
Is that supposed to be the expected behavior? Or should EF Core just skip the generation of an empty .cs file? I can't find any reference to this in the documentation.
I have taken my main project and stripped out all the code up to the bare minimum to find out whether is the behavior or some sort of bug in my configuration.
Below the minimum core to reproduce generating empty Up/Down methods with no change in models, with the following Nuget packages:
Microsoft.EntityFrameworkCore 2.2.6
Microsoft.EntityFrameworkCore.SqlServer 2.2.6
Microsoft.EntityFrameworkCore.Tools 2.2.6
Microsoft.NETCore.App 2.2.0
namespace TestingEFCore
{
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<BloggingContext>
{
public BloggingContext CreateDbContext(string[] args)
{
var connectionString = "Server=localhost;Database=TEST2;Integrated Security=SSPI;";
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlServer(connectionString);
return new BloggingContext(optionsBuilder.Options);
}
}
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
}
I would expect no XXXXXX_noChangeInModel.cs being generated, but a I get migrations with empty Up/Down methods. I can't find the documentation to describe this use case.
I think it is expected behavior. Consider the case when you have no changes in model but you need to add some data in your db like this
public partial class your_migration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(#"your sql");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(#"sql to clean up data");
}
}
Without an empty migration for no changes in model generated it would be impossible to obtain such migration.

EF not creating identity table when trying to create new database

I have 2 model classes:
Customer.cs with name and Id
Movies.cs with name and Id
I tried to run enable-migrations, but I got this error:
No context type was found in the assembly WebApplication2'.
Then I saw some answers on websites and people told to make a DBContext class. I do not have any DBContext class as I just made a new MVC project.
So, I tried to make a DbContext class of my own as follows:
{
public class MyDBContext:DbContext
{
public void MyDbContext()
{
}
}
}
Then I was able to run enable-migrtaions command and Migration folder was created with configuration.cs as follows:
internal sealed class Configuration : DbMigrationsConfiguration<WebApplication2.Models.MyDBContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(WebApplication2.Models.MyDBContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
}
}
}
Now when I run the add-migration Initialmodel the Up() and Down() methods are empty and there are no Identity tables.
Please help !
First off I suggest you refer to creating a new MVC project using Entity Framework. There are a lot of tutorials but here's the Microsoft one which is accurate and pretty complete:
Get Started with Entity Framework 6 Code First using MVC 5
It also includes a section on Migrations, however you don't need Migrations until you have a database and a model that's changing.
I would suggest backing out your Migrations until we're ready for them. Rick Strahl has a good article on how to back them out and get back to a clean state:
Resetting Entity Framework Migrations to a clean State
Finally, your DbContext class has to have a DbSet. A DbSet class is an entity set that can be used for create, read, update, and delete operations. With your DbContext class as it is, Entity Framework has no idea what to do or map.
Change your DbContext class to something like this:
{
public class MyDBContext:DbContext
{
public void MyDbContext()
{
}
public virtual DbSet<Movie> Movies {get; set;}
public virtual DbSet<Customer> Customers {get; set;}
}
This will allow you (say in a Controller) to do something like this to add a new Customer to the database:
var customer = new Customer { name = "John Smith" };
using(var context = new MyDbContext())
{
context.Customers.Add(customer); // adds the customer to the DbSet in memory
context.SaveChanges(); // commits the changes to the database
}
NOTE: I don't recommend creating a DbContext this way in a controller, in the first link on using EF6 with MVC 5 there are better ways.
Hope that helps.

Enable migrations with reference to ApplicationUser identity framework code first

I'll create a database with identity framework (code first way) but I've errors when I run code below in the package manager.
PM> Enable-Migrations -ContextTypeName FreeTime.AspMvc.Context.FreeTimeContext -Force
Here are my errors:
IdentityUserLogin: : EntityType IdentityUserLogin has no key defined. Define the key for this EntityType.
IdentityUserRole: : EntityType IdentityUserRole has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet IdentityUserLogins is based on type IdentityUserLogin that has no keys defined.
IdentityUserRoles: EntityType: EntitySet IdentityUserRoles is based on type IdentityUserRole that has no keys defined.
More information:
(Click to see full screen)
In other classes I've made a property type of ApplicationUser named UserId and one of type of string named User for holding witch user has made witch topic. Here you've an example:
public class Topic
{
[Key]
public int TopicId { get; set; }
[ForeignKey("dbo.AspNetUsers.Id")]
public string UserId { get; set; }
public ApplicationUser User { get; set; }
}
Small update: Here is my context file:
public class FreeTimeContext: DbContext
{
public DbSet<Topic> Topics { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
I've also seen that there is a second context file named ApplicationDbContext.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("FreeTimeContext" /* --> this I've edited into my own name */,
throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
Big update: In a later state I've tried other things like list below:
First I've tried to enabled the migrations for ApplicationDbContext. Here are the steps I've done.
First I've run this code:
PM> enable-migrations -ContextTypeName FreeTime.AspMvc.Models.ApplicationDbContext -ForceThis is done without errors.
Then I've run this:
PM> add-migration "initAspTables"
Also no problems with this code.
Finaly I've update my database:
PM> Update-Database
Also done with no problems.
Check if the tables are created into the server manager → Check but doesn't contain my own tables. ☹
Conclusion: not really what I will have.
Second thing I've done is inherit FreeTimeContext from ApplicationContext instead of DbContext like code below.public class FreeTimeContext: ApplicationDbContext
{
public DbSet Topics { get; set; }
public FreeTimeContext(): base()
{ }
// other code
}And again to try enable the migrations with this code:
PM> enable-migrations -ContextTypeName FreeTime.AspMvc.Context.FreeTimeContext -Force
but I've this error:
The ForeignKeyAttribute on property UserId on type FreeTime.AspMvc.Models.Topic is not valid. The navigation property dbo.AspNetUsers.Id was not found on the dependent type FreeTime.AspMvc.Models.Topic. The Name value should be a valid navigation property name.More information:(Click to see full screen)Conclusion: didn't work.
Can you help me? I don't know what else I could do to migrate the class ApplicationUser together with my own classes to the database.

Renaming dbo.AspNetUsers table

I'm trying to rename the default table names generated by ASP.net Identity 2.0. I read all the articles, the questions and the answers on stackoverflow but im still getting the same error.
I renamed the tables to Roles, UserClaims, Logins, UserRoles and Users. I also changed the application dbcontext to the following
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>().ToTable("Users", "dbo");
modelBuilder.Entity<IdentityRole>().ToTable("Roles", "dbo");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles", "dbo");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims", "dbo");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins", "dbo");
}
}
But i keep getting the Invalid object name 'dbo.AspNetUsers'. error, and I have no idea why its still trying to locate AspNetUsers in the first place instead of just Users although i made the changes above. Totally desperate by now.
The database as well, same columns with the new table names:
And the SQL database project:
You need to update database. Enable-Migrations and Update-Database, explained in details here. The point of EF code first approach is to write our model classes and configurations and each time we change something we use EF migrations to update the database schema.
Database first approach with asp.net-identity-entityframework are explained here and here, not so straightforward
Write the following code in IdentityModels.cs
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DBConnectionString", throwIfV1Schema: false)
{
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
modelBuilder.Entity<IdentityRole>().ToTable("Roles");
modelBuilder.Entity<ApplicationUser>().ToTable("Users");
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
Write the following code in Application_Start() Method in Global.asax.cs file
Database.SetInitializer<ApplicationDbContext>(null);

Model change detection ASP.NET code first migrations

I have added
public IEnumerable<Comment> Comments { get; set; }
to a Model in an ASP.net MVC project. I ran the following to generate a migration in the package console
PM> Add-Migration AddCommentsToDevice
and the resulting migration did not pick up the change to the model
public partial class AddCommentsToDevice : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
Any tips on the syntax of the migrations or what causes detections?
You've added to little. You need to configure the relationship properly - the best with fluent api. Use this for navigation property:
public virtual ICollection<Comment> Comments { get; set; }
Important - always use ICollection, not IEnumerable for Navigation properties and make them virtual - thanks to this ef will be able to track changes.
Then in your DbContext you add following code:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Model>().HasKey(x => x.Id);
modelBuilder.Entity<Model>().HasMany(x => x.Comments);
base.OnModelCreating(modelBuilder);
}
I assumed that class related to Comments is named Model.

Resources