Entity Framework Migrations not Detecting Model Change - entity-framework-4.3

I'm trying to start using EF Migrations with an existing database.
The startup project is an MVC 3 project and the domain objects are in a separate project of the same solution.
Here are the steps I took:
Add-Migration InitialMigration -IgnoreChanges -Verbose
Created Configuration.cs and ###_InitialMigration.cs. Had to edit Configuration.cs to add the name of my context object as it is in a separate project.
Update-Database
Added dbo.__MigrationHistory to my database
Added a new property to an existing class
private ulong? myProp;
[DataMember]
public ulong? MyProp
{
get { return myProp; }
set
{
if (myProp != value)
{
myProp = value;
RaisePropertyChanged(() => this.MyProp);
}
}
}
Successfully compiled the solution.
Add-Migration MyNewMigration
Created ###_MyNewMigration.cs, with no migrations in it:
public partial class MyNewMigration : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
Not looking good... where are the migrations?
Update-Database -Verbose -Script
No mention of the new property in the upgrade script
INSERT INTO [__MigrationHistory] ([MigrationId], [CreatedOn], [Model], [ProductVersion])
VALUES ('201206122137444_MyNewMigration', '2012-06-12T22:07:49.170Z', 0x1F8B080YadaYada, '4.3.1')
How can I get EF Migrations to pick up the model change?

It turns out that EF Migrations does not like the ulong? data type I used. That property was ignored without any warning.
Changing the type to long? allowed the migration to succeed.

Related

Database still doesn't show Identity columns after Add-migration and Update-Database Done

I created a Web API with classical data layer access class ApplicationContext
public class ApplicationContext: DbContext
{
public ApplicationContext(DbContextOptions<ApplicationContext> options)
: base(options)
{
}
public virtual DbSet<Thing> Things{ get; set; }
}
Then i successfully added a frist Initial migration and update-database for adding columns in database.
After i had to change my ApplicationContext : DbContext to ApplicationContext : IdentityDbContext in order to get default identity tables form EmtityFramworkCore.Identity into my Database.
So i executed again a Add-Migration AddedIdentityTables for a new migration with IdentityData and i got them into a new Migration, after Update-Database i successfully got Identity columns in last Snapshot of Database im Migration folder, but there were literally no identity columns in the database
What am i doing whron?

Initial migration source file does not contain schema for database

I am using entity framework 6 with Web API. I have applied Enable-Migrations command in package manager console and Migration folder created with Configuration class.
I have executed Add-Migration -InitialCreate command initial migration source file created but up and down methods are empty.
so when I recreate the database no table is created except migrationhistory table. No table is created into database so my API cannot perform any POST, GET operation and getting below error message.
Exception type: System.Data.SqlClient.SqlException
Message : Invalid object name 'dbo.Template'.
Please assist me.
I have put my connection string in database.config in startup project not in Web.config of startup project reason behind this was I didn't want to start Web API when database name changes in Web.config. I have attached my Web.config snapshot.
MigrationHistory Table
Below is code for DBContext class.
public class TestDBContext : DbContext
{
public DbSet<SamlNode> SamlNodes { get; set; }
public DbSet<Template> Templates { get; set; }
private static string connectionString
{
get
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath);
ConnectionStringsSection connectionString = (ConnectionStringsSection)config.GetSection("database");
if (connectionString != null && connectionString.ConnectionStrings["TestDBContext"] != null)
{
return connectionString.ConnectionStrings["TestDBContext"].ConnectionString;
}
}
}
public TestDBContext()
: base(connectionString)
{
Database.SetInitializer<TestDBContext>(new CreateDatabaseIfNotExists<TestDBContext>());
//Database.SetInitializer(new MigrateDatabaseToLatestVersion<TestDBContext, Migrations.Configuration>(connectionString));
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
Regards,
Rashi

How to correctly override the SaveChanges function in EF 4.1

I need to automatically insert the current date when I create a new order in my EF 4.1 MVC3 web application. I also need to automatically add the currently logged in user - I'm using forms authentication.
After searching the web, I found that I need to override the SaveChanges() function and an article on StackOverflow showed how to do this: Entity Framework 4.1 Automatic date. However, I couldn't get the code to work.
Where does this code go?
How do I find out what is?
Sorry if the question is trivial - I'm new to EF.
B.
You can override in your context class,
public partial class YourDbContext: DbContext
{
public YourDbContext()
{
}
public override int SaveChanges()
{
// do your additional stuff here.. (Ex:- save current user)
return base.SaveChanges();
}
}
And the other option is you can set default values in the constructor of your entity,
Public class YourEntity{
public YourEntity(){
CreatedDate=DateTime.Now;
}
Public DateTime CreatedDate{get;set;}
}

Convert IQueryable<T> to IQueryable<Y>

I'm try to do this : I'm using EF code first to map an old existing database. There's many fields with the wrong type (ex: char(1) used as boolean) so I've created a wrapper class for my db context that maps perfectly to the database table. Now, I want to expose an IQueryable of my Entity type on my repository. See my example :
public class MyContext:DbContext
{
public DbSet<WrappedEntity> WrapperEntities;
}
public class Repository
{
private MyContext _context;
//contructors omitted
public IQueryable<Entity> GetEntities()
{
return _context.WrapperEntities; //doesn't compile, I need some convertion here
}
}
I already have my convertion routine, the only thing missing is a way to query my DbContext thought my repository without exposing the WrappedEntity class, Is it possible and how ?
Thanks.
Usually you project with Queryable.Select to change the type of your query...
public IQueryable<Entity> GetEntities()
{
return _context.WrapperEntities.Select(x => new Entity(){...});
}

Entity framework asp.net MVC3 .NET 4

I Have a little snag. With my asp.net mvc3 application.
When I trying to compile my app I obtain this Error
Error 2 'Blog.Domain.Concrete.EFEntryRepository' does not implement interface member 'Blog.Domain.Abstract.IEntryRepository.SaveEntry(Blog.Domain.Entities.Entry)' D:\dokumenty\Visual Studio 2010\Projects\MVC3\Blog\Blog.Domain\Concrete\EFEntryRepository.cs 10 19 Blog.Domain
This is my Interface.
namespace Blog.Domain.Abstract
{
public interface IEntryRepository
{
IQueryable<Entry> Entries { get; }
void SaveEntry(Entry entry);
void DeleteEntry(Entry entry);
}
}
And this is my implementation of it.
public class EFEntryRepository : IEntryRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<Entry> Entries
{
get { return context.Entries; }
}
public void SaveEntry(Entry entry)
{
if (entry.EntryID == 0)
context.Entries.Add(entry);
context.SaveChanges();
}
public void DeleteEntry(Entry entry)
{
context.Entries.Remove(entry);
context.SaveChanges();
}
}
This is link to my project. http://sigma.ug.edu.pl/~kkubacki/Blog.zip //NEW
Now I is compiling.
What I Do Wrong ?
I have new Information about the bug. Now the solution is compiling but the application crashes with the bug information
"{"The type 'Blog.Domain.Concrete.Entry' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject."} " Visual studio shows bug in the EFEntryRepository class.
I don't know what to do please help.
OK Problem IS Solved.
You have two different Entry classes in different namespaces.
Blog.Domain.Entities.Entry
Blog.Domain.Concrete.Entry
The interface is referring to one and the implementation is referring to the other.

Resources