EF 6 Code First ASPIdentity Tables in separate database - ef-code-first

I'm using EF6 Code First.
I have a class library "IdentitySecurity" that contains a context "IdentityDBContext" that points to an "IdentitySecurity" database and the IdentityModels.
I then have my web project that contains a context "ProjectDBContext" that points to a "Project" database and the ProjectModels.
If I create a model in ProjectModels like this:
public class Project
{
public int ProjectId { get; set; }
public virtual IdentitySecurity.Models.ApplicationUser UpdateUser { get; set; }
}
It can't create a migration, I think it is because it can't make a foreign key relationship to another database and expects it to be in the Project database.
The error it gets when you try to create a new migration is this:
One or more validation errors were detected during model generation:
Project.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
Project.Models.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.
Another example I ran into similar to this is I had a config table that multiple applications use in a common database area. I attempted to reference this in a model like this:
public virtual Common.Models.CommonItem CommonItem { get; set; }
In this situation, it added the migration and updated the database without error, but what it did is actually create the table "CommonItem" in the Project Database instead of using the one in the Common database.
Is there a way to set up EF6 CodeFirst so I can have configuration tables or ASPIdentity tables in another database, and still reference them as virtual objects?
Thank you.

I'm afraid for foreign key references you'll have to move everything into one DB and have ProjectDbContext to inherit from IdentityDbContext.
Sql Server does not support foreign keys across databases.

Related

How to scaffold AspNetUserRoles table?

I have tried to scaffold a AspNetUserRoles table with AspNetUser, AspNetRoles and others tables that I need.
The scaffolding has a problem with many to many relationship of AspNetUserRoles and there is an error when application runs
System.InvalidOperationException: 'Cannot use table 'AspNetRoles' for entity type 'IdentityRole' since it is being used for entity type 'AspNetRole' and potentially other entity types, but there is no linking relationship. Add a foreign key to 'IdentityRole' on the primary key properties and pointing to the primary key on another entity type mapped to 'AspNetRoles'.'
Or other similar errors. I tried to handle AspNetRoles for a day.
I could scaffold a ASPNetUserRoles table only and copy paste it's fragment to my DbContext.
Is it the right way to add ASPNetUserRoles CRUD pages?

How do I generate an initial/base migration for existing Symfony+Doctrine application?

If I already use migrations, I can easily generate incremental one using:
app/console doctrine:migrations:diff.
But assume I have an existing application that does not use migrations yet. doctrine:migrations:diff will just generate a diff between the current database schema and doctrine entities. The problem is I need to have an initial/first migration consisting of CREATE TABLE for every entity created up to this point. My current workaround is to create an empty database, switch credentials in parameters.yml, and run doctrine:migrations:diff then.
I don't like this solution - is there a better one?
you could use doctrine:schema:create --dump-sql to generate the sql for creation and put this into the first migration version
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/tools.html#database-schema-generation
If the table does not exist as a Doctrine Entity, you'll need to manually create a migration class for it, as well as any separate Fixtures.
<?php
namespace DoctrineMigrations;
use DoctrineDBALMigrationsAbstractMigration,
DoctrineDBALSchemaSchema;
class Version00001 extends AbstractMigration
{
public function up(Schema $schema)
{
$this->addSql('CREATE TABLE MY_CUSTOM_PREFIX_example (id INT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) ENGINE = InnoDB');
}
public function down(Schema $schema)
{
$this->addSql('DROP TABLE MY_CUSTOM_PREFIX_example');
}
}
Also make sure that you exclude these custom tables using filters within your Doctrine configuration (#see: http://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html#manual-tables)
For this example you'd replace t_ with MY_CUSTOM_PREFIX_
And what about a little :
bin/console doctrine:migrations:diff --from-empty-schema
With the flag --from-empty-schema it will do exactly what you're asking for.
After that you can (must) manually add an entry in the doctrine_migration_versions table if the DB is already set up and you want to (have to) run /bin/console doctrine:migrations:migrate. Like that (screenshot from adminer):

Is it possible to make one-to-one relationship with EF Code First Fluent API if there is not foreign keys

I have two tables, Users and UserSettings.
There're mapped on two classes, User and UserSetting
Both have a UserID column, acts as a PK
Every record in Users table has a record with same UserID in UserSettings table, and vice-versa.
There is no foreign key relationships between this tables.
Is it possible to create property of type UserSetting in User (1-1 relationship) without changing the database structure.
Adding public virtual UserSetting UserSetting {get;set;} into UserClass, and then
this.HasOptional(t => t.UserSetting).WithRequired(); into UserMap fluent mapping class
doesn't help.

Entity Framework Code First Migrations: Set Primary Key Value

I have a table that stores some extra data for some rows of a table like:
public class QuoteExtra
{
[Key]
public int QuoteId { get; set; }
// More fields here
}
I'd like to be able to add rows to this table where I explicitly set the PK.
If I simply leave it as above, setting a value and submitting the row causes the value to be discarded and replaced with the auto-generated value from the database (and the column is defined as an Identity column in the actual schema).
This appears to be the right solution:
public class QuoteExtra
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int QuoteId { get; set; }
// More fields here
}
However this instead gets me the exception:
Cannot insert explicit value for identity column in table 'EnumTest' when IDENTITY_INSERT is set to OFF.
So, how do I write my class so that I'm able to set the value of a Primary Key in EF?
Edit:
I tried adding the following Code-based Migration to set IDENTITY_INSERT to ON:
public override void Up()
{
Sql("SET IDENTITY_INSERT QuoteExtra ON");
}
I ran it and tried again, but got the same exception as above. What's strange is the database does reflect this setting, and running SQL against it directly does allow me to insert arbitrary values in for the primary key - so it would appear Entity Framework itself is enforcing this rule, and neglecting to recognize that IDENTITY_INSERT is not in fact set to off. Do I need to set it somewhere in EF itself?
Edit 2:
I misunderstood IDENTITY_INSERT; I assumed setting it once left it on for that table indefinitely. In fact it lives as long as the "Session," meaning that for example setting it in a Migration means it lives... as long as that Migration runs, and has no bearing on future connections like my later .Add() with EF, which explains why I still got that exception - the DB really is the source of the exception, not EF. Since IDENTITY_INSERT is limited to at most one table per session it's a fairly inefficient way to do this - not creating an Identity PK column in the first place seems like a better route.
This is the proper way of creating a PK without Identity Autoincrement enabled:
public class QuoteExtra
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int QuoteId { get; set; }
// More fields here
}
However, if you add DatabaseGenerated(DatabaseGeneratedOption.None)] after EF Migrations has already created the table, it quietly does nothing to the table. If this is your scenario you need to add a manual migration to drop the table:
add-migration RecreateQuoteExtra
And in the migration:
public override void Up()
{
DropTable("QuoteExtra");
}
EF Automatic Migrations will then automatically recreate the table without the Identity constraint, which will then allow you to set the PK value anytime, without having to run any special commands like IDENTITY_INSERT ON.
It sounds like a less destructive way to do this is coming in EF7 ("Data Motion"), or you could write a lot of manual sql yourself in the migration to create temp tables and move data around if you wanted to avoid losing existing data in the table.
EDIT: Depending on your scenario EF Migrations might not recreate the table - if the class already exists and is already added to your DbContext it will just drop it and leave it at that, meaning your manual migration has to not only drop but also create the table. Not a big deal since the scaffolded code EF Migrations generates for you from add-migration will create these statements for you, but it is a bit more code to check over for issues.
It is right solution but only for a new table. If you change database generated option for an existing table, EF migrations are not able to perform this change and your QuoteId column is still marked as Identity in the database.
I could'nt solve this Problem with your Hints then i've tried to re-create the whole Database but it wasnt working, too.
To fix this you have to remove the identity: true property on the first(!) creation of the Column (e.g. Initial-Migration).
Maybe it will help someone..

Does an Entity Framework Foreign Key Association Always Imply Cascade Delete?

After reading Foreign Keys in the Entity Framework I tried adding a Foreign Key relationship to an EF 5 Code First application (the app uses Independent Associations to date).
I noticed that the generated DDL includes a cascade delete. This is the opposite of the behavior with Independent Associations.
Given that a Foreign Key relationship is created in EF Code First by adding an int property named according to the convention ClassnameId, is it possible to have a non-cascading delete? If so, what value would be assigned to ClassnameId to disassociate the related object without deleting it from the database?
If you explicitly declare a foreign key, that is non nullable, EF will assume that you want a cascading delete.
You can either make the Foreign key nullable:
public int? YourFkId {get;set;}
Or you can use fluent notations in your OnModelCreating
modelBuilder.Entity<Class1>()
.HasMany( c => c.Class2s )
.WithRequired(x => x.Class1 )
.WillCascadeOnDelete(false);

Resources