Entity Framework Code First Migration and Data Migrations - entity-framework

We are using Entity Framework Code First with Migrations. We have it running without any issues. We are trying to migrate data from an old database to the new. We need to drop the database, create all the tables, insert the data and then add in the primary keys and foreign keys. We want to do this in EF so that we can format the data being migrated. We have been successful in creating the database and then migrating the data over but the primary keys are in the old database are not coming over. I've tried using the ExecuteSqlCommand before a bulkinsert:
ctx.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[TableName] ON");
but this does not work because the migration scipts have the idenity set to true:
Id = c.Int(nullable: false, identity: true),
Is there a way to set the identity to false then after the data is inserted into the database, set the identity to true?

You are doing it in the right way (Id is an identity and you enable identity insert). SET IDENTITY_INSERT ON is valid only for the session (the connection) so you need to use only one connection.
Also, you have to seed the database using INSERT statements (and not EF SaveChanges).

Related

EF does not generate every model from database using SQLite

I am trying to change the service based database in my project to SQLite. I am using EF database first approach but the EF does not generate every model from database. Eventhough foreign keys are set it does not generate the connections and also returns an error:
> Error 6005: The data type '' is currently not supported for the target Entity Framework version; the column 'Id' in the table 'main.Comments' was excluded.
It does so with every table that has an Id column (integer, primary key).
How can I fix this?
Thanks

Adding a primary key into an existing table using Entity Framework Core

I have an existing, populated table. Using an EF Core migration, I want to create a DB Generated Primary Key.
Here's my fluent API:
modelBuilder.Entity<MyTable>()
.HasKey(a => a.Id);
modelBuilder.Entity<MyTable>()
.Property(p => p.Id)
.ValueGeneratedOnAdd();
The issue that I have is that, when I run migration, I get an error, because the existing rows in the table do not have this (new) field populated:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.MyTable' and the index name 'PK_MyTable'. The duplicate key value is ().
Is there a way that I can leverage the default value to retrospectively populate this table with primary keys? Alternatively, is there another way to populate this field retrospectively?
Alternatively, is there another way to populate this field retrospectively?
Yes. But not through EF. You'll need to clean up the database manually before EF can start managing the schema.

Entity Framework Generate Database Schema (SQL) with Default Table Values

I am using EF 5 and SQL Server 2005, Model First (sort of).
By sort of, I mean that I typically build my schema in the SQL Server designer, but import the schema into EF so I have a visual view. There is often round-tripping.
However, I noticed that when I try to generate the DB schema based on the EF model, it skips all of the NEWID() default values that I have assigned as default values to my Guid IDs, but it doesn't skip the identity fields of type int.
I found this post explaining the reasoning for this:
Entity Framework 4 and Default Values
However, it doesn't answer my question: How do I get Entity Framework to generate a SQL DDL database schema with default values of NEWID() for my uniqueidentifier types?
NOTE:
I don't care about how to set them from the POCO entities and so forth (there are plenty of posts describing that) - my concern is getting the SQL DDL generated right so I can seed the database without worrying about these values going missing.
Using Entity Framework Migrations, you can use the GUID column builder and its DefaultValueSql parameter. The value of that parameter can be the string "NEWID()". This should take care of proper DDL generation.
Next you should declare these properties as database-generated using attributes or the fluent model builder, so that EF ignores the values set in your POCOs (which will be null for new objects).

Existing Azure Database with Entity Framework 6 Alpha 2

I have a database on azure where clustered indices are required. I would like to use Entity-Framework 6 Alpha 2, because I would like to use the new async features. When I test it on my local machine with SQL Express 2012 everything is fine, but when I try it with my azure database I get the following error:
Tables without a clustered index are not supported in this version of SQL Server. Please create a clustered index and try again.
I have no idea what to do, because when I test it with an empty database every primary key is a clustered index.
Any ideas?
Would you add a bit clarification on your situation with "Existing Database on Windows Azure" and using with EF 6? First of all - are you using EF CodeFirst, ModelFirst, DatabaseFirst?
Then if you really have existing database, how did you create it? DB + Schema manually, using some wizard (SSMS, SQL Azure Migration Wizard, EF CodeFirst created it, etc?). How this existing DB ended being in Azure?
Then trace down the full error message, check for which table it happens and manually add the clustered index on that table. It is true that every primary key you create in SQL Server, by default is also a CLUSTERED. But if the table was created first, then the Primary Key was added as separate DDL statement (ALTER TABLE ....) it might not have been created as CLUSTERED.
So, the message is pretty clear - please create clustered index first. Find out which table is SQL Azure complaining about and create a clustered index on it. If it hasn't Primary Key, just add one as CLUSTERD:
ALTER TABLE [dbo].[Individual]
ADD CONSTRAINT [PK_Individual_CustomerID]
PRIMARY KEY CLUSTERED
(
[CustomerID] ASC
)
If it has a primary key - check which columns are included, drop it, and recreate it as clustered.

Using IDENTITY_INSERT with EF4

I am trying to create a record in the db that has a predefined primary key value. I know how to do this with sql, but I was wondering if EF can do this for me? Otherwise, I will have to create a stored proc for the inserts.
In case you have the StoreGeneratedPattern attribute set to "None" for your entity, the Entity Key value you specify for it will be passed to database.
In case this attribute is set either to "Identity" or to "Computed" there is no way to control what value will be set to this column in DB.
So, if you have an auto-incremented column in your database and the ADO.NET Entity Data Model wizard has set the StoreGeneratedPattern for you, you can manually change this attribute to "None" in the SSDL part of the model using XML Editor, and then enable IDENTITY_INSERT.
You can use the ObjectContext.ExecuteStoreCommand method if you are using EF4 or use the ObjectContext.Connection.StoreConnection property to execute a SQL command SET IDENTITY_INSERT <Your_Table> ON (both in EF1 and EF v4).