If a class and its table are renamed how does the migration know to generate RenameTable? - entity-framework-migrations

I have a very simple context
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace WindowsFormsApplication1
{
[Table("MyParts2")]
public class MyPart2
{
[Browsable(false)]
[Key]
public int Id { get; set; }
}
public class EFProjectDbContext : DbContext
{
public EFProjectDbContext() // used for migrations
: base("name=ApplicationDatabase")
{
Database.SetInitializer(new CreateDatabaseIfNotExists<EFProjectDbContext>());
}
public EFProjectDbContext(string connectionString)
: base(connectionString)
{
if (Database.Exists())
{
// error here is benign uncheck break
var isCompatible = Database.CompatibleWithModel(false); //error occurs here
if (!isCompatible)
{
// uncheck break when this exception type is shown
// note if you are in debug you need to run exe to kick off upgrade
throw new Exception(
"The database is not compatible with the entity model. Drop the database or run migrations");
}
}
else
{
Database.SetInitializer(new CreateDatabaseIfNotExists<EFProjectDbContext>());
}
}
public EFProjectDbContext(DbConnection connection)
: base(connection, false)
{
}
public DbSet<MyPart2> MyParts2 { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
}
And i have migrations enabled
If I rename the class name and table attribute and create a migration the up method creates as
public override void Up()
{
RenameTable(name: "dbo.MyParts2", newName: "MyParts3");
}
How does it the create migration realise that the table is a rename and not a drop and re-create ?

Related

Entity Framework code-first migration: revert migration not working using down() method

I have successfully add new column in table using Add-Migration AddMobileNo using Entity Framework code-first approach.
[Table("Student")]
public class Student
{
[Key]
public int StudentId { get; set; }
public string Name { get; set; }
// Add new column using "Add-Migration AddMobileNo"
public string MobileNo { get; set; }
}
public partial class AddMobileNo : DbMigration
{
public override void Up()
{
AddColumn("dbo.Student", "MobileNo", c => c.String());
}
public override void Down()
{
DropColumn("dbo.Student", "MobileNo");
}
}
Now I am trying to revert a migration using this command for calling down() method:
update-database -TargetMigration: "AddMobileNo"
but it's not working for me and showing this message in PMC (Package Manager Console):
Target database is already at version AddMobileNo
Thanks in advance.

Populate a model from database ASP.NET MVC

I have the following model:
namespace Factura.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("factura.marfa")]
public partial class marfa
{
[Key]
public int idmarfa { get; set; }
[StringLength(45)]
public string denumire { get; set; }
public int idfurnizor { get; set; }
}
}
And I have also a class that inherits DbContext:
namespace Factura.Models
{
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class FacturaContext : DbContext
{
public FacturaContext() : base("name=FacturaContext")
{
}
public virtual DbSet<marfa> marfas { get; set; }
[...]
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
[...]
}
}
}
In my controller I have the following code:
namespace Factura.Controllers
{
[Authorize]
public class CumparatorController : Controller
{
FacturaContext dbFactura = new FacturaContext();
[HttpGet]
public ActionResult Cumparaturi()
{
var marfas = dbFactura.marfas.ToList();
return View(marfas);
}
}
}
The problem I have is that dbFactura.marfas is null, it doesn't bring anything from Database even if the table is populated.
Can anyone help me with this?
Thank you!
Remove [Table("factura.marfa")] from marfa class and add the following in your OnModelCreating in FacturaContext
modelBuilder.Entity<marfa>().ToTable("factura_marfa"); //updated . with _
Create the migration & run

Update-Database not updating identity tables

I am trying to update my database by using automatic migrations. I have recently added some properties to the Identity Model:
namespace CISC_Website.Models
{
public class ApplicationUser : IdentityUser
{
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool ConfirmedEmail { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("CISCDb")
{
}
}
}
However whenever I run the update-database command these changes are not pushed as my user tables are still the same as when they were first created.
Here is the contents of my migrations folder:
namespace CISC_Website.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Collections.Generic;
internal sealed class Configuration : DbMigrationsConfiguration<CISC_Website.Models.CISCDb>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(CISC_Website.Models.CISCDb context)
{
//seed data...
}
}
}
I know originally when the enable migrations command was run, the identity model was represented as such:
namespace CISC_Website.Models
{
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
}
Any idea how i can get these tables recognized??
Your application has two DbContexts: CISCDb and IdentityDbContext and you have configured migrations only for your CISCDb context. Therefore changes in the Identity context are not included in the CISCDb migrations.
You should be able to configure the migrations for the IdentityContext the same way you did for the other context to get it working.

Entity Framework Auto Migration

Hi I am learning to develop project using code first approach. I am facing a small problem that when i run the command Add-Migration its not identifying the changes even i have enables the AutomaticMigrationsEnabled in config file
here is my code
----------------------------- DbContext file
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntityCodeFirstSample.DataBaseFiles
{
class EntityCodeFirstSampleContext : DbContext
{
public EntityCodeFirstSampleContext()
: base("name=DbConnectionString")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<EntityCodeFirstSampleContext, EntityCodeFirstSample.Migrations.Configuration>("DbConnectionString"));
}
public DbSet<Publisher> Publishers { get; set; }
public DbSet<Book> Books { get; set; }
public DbSet<Sample> Samples { get; set; }
public DbSet<Venkat> Venkats { get; set; }
}
}
----------------- Configurations file ---------------------------------
namespace EntityCodeFirstSample.Migrations
{
internal sealed class Configuration : DbMigrationsConfiguration<EntityCodeFirstSample.DataBaseFiles.EntityCodeFirstSampleContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(EntityCodeFirstSample.DataBaseFiles.EntityCodeFirstSampleContext context)
{
}
}
}
------------------------------------------- Model File ---------------------
namespace EntityCodeFirstSample.DataBaseFiles
{
[Table("Venkat")]
public class Venkat
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public int NotaryCode { get; set; }
}
}
After running the command Add-Migration VenkatClass it is generating the migration file as below
namespace EntityCodeFirstSample.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class VenkatClass : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
when AutomaticMigrationsEnabled = true then you don't have to add Migration because when you will execute your program the EF will look after for any change on the fly and update your database. If you want to control then set the AutomaticMigrationsEnabled = false. Then you should be able to see the difference when Add-Migration is being called.
Please read: https://msdn.microsoft.com/en-us/data/jj554735.aspx
and then read this: https://msdn.microsoft.com/en-us/data/jj591621.aspx
Run:
update-database
Make sure that the project is set default where the connection string is stored.
If it does not return any error then it is all good to go. You should able to see that the update has already occured and your new changes must have reflect already.

Entity Framework added s to my .dbo

I using "Entity Framework DbContext" at the moment I have got exception towars.dbo was not found. This is very strange because in my website I all the time ask about towar.dbo but no towars.dbo Do you know where is a problem?
- InnerException {"Invalid object name 'dbo.Towars'."} System.Exception {System.Data.SqlClient.SqlException}
My all things about Towar (of course different place in my program):
public class ProductController : Controller
{
//
// GET: /Product/
public ITowarRepository repository;
public ProductController(ITowarRepository productRepository)
{
repository = productRepository;
}
public ViewResult List()
{
return View(repository.Towar);
}
}
public interface ITowarRepository
{
IQueryable<Towar> Towar { get; }
}
public DbSet<Towar> Towar { get; set; }
public class EFTowarRepository : ITowarRepository
{
public EFDbContext context = new EFDbContext();
public IQueryable<Towar> Towar
{
get { return context.Towar; }
}
}
public class Towar
{
[Key]
public int Id_tow { get; set; }
public string Nazwa { get; set; }
public string Opis { get; set; }
public decimal Cena { get; set; }
public int Id_kat { get; set; }
}
Add the following line to your context:
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
You can tell EF to map to the table Towar by overriding the OnModelCreating method in your DBContext class with fluent API like this:
public class EFDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Towar>().ToTable("Towar");
}
}
Now EF will look for Towar table instead of Towars. If you do not have these tables created, there is some other problem you are having.
EF Code First automatically pluralizes the table names. Use a [Table] attribute to explicitly map the entity to a table name:
[Table("Towary")]
public class Towary
{
// Whatever properties
}
It looks like there's a way to disable pluralization gobally too, see Entity Framework Code First naming conventions - back to plural table names?.
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MVCDemo.Models
{
public class EmployeeContext : DbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
For the sake of completeness #forty-two

Resources