How can I set the schema dynamically for a Code First DbContext? - ef-code-first

I have an EF6 Database First application that uses tables generated to an edmx from the dbo schema.
To update certain large pricing tables that work in concert with each other, I create new tables in a new schema based on the date, then inside a transaction, move the current tables to a backup schema, and move the new tables to the dbo schema. This is implemented using a new MetadataWorkspace created by reading the edmx file and changing the schema, and allows me to have two DbContexts where one works with the existing data in the dbo schema, and the other works with the new tables in the new schema. And works great for Database First!
See this SO article.
For CodeFirst, one can set the modelBuilder.HasDefaultSchema in OnModelCreating, but then the DbContext is locked down, and OnModelCreating is not called again for new DbContext instances, so whatever schema was set is now used for all such DbContexts for the duration of the application.
My question is – how can I dynamically change the DbContext with CodeFirst where I can have two DbContext, each using different schema? I cannot just define two DbContext derived classes since the schema name is dynamic.

Apparently this cannot be done but once since the DbContext is locked down and keeps the schema name. I plan to address this need by keeping the second schema name fixed rather than dynamic. Would be nice if could "clone" the locked down DbContext with a new schema name but currently not possible anyway that I have found. Closing.

You can set the the schema dynamically in EF6. You need to adjust the way you initialize your DBContext though.
I found most of what I was looking for here:
Multi-Tenant With Code First EF6

Related

Symfony Mapping in Doctrine without Annotations or XML Files

a customer has an existing database. The schema is often changed within the database itself (e.g. he adds a new column).
My task is to develop an admin area with symfony that automatically reacts on table schema changes without modifying the application code. E.g. the customer adds a new column to table "MyEntity", and the application automatically generates a new column in the accordingly list view.
My approach is to dynamically map the table columns to the Entity class so that ALL Attributes and ALL Getters/Setters are generated dynamically from the table schema.
So is it possible to map the table columns in a Doctrine Entity without the use of Annotations or XML Files.
Something like:
class MyEntity{
public function generateMappingFromSchema($sTableName){...}
}
Please don't do that. Doctrine was not designed for such use case.
There is a library though you should check https://github.com/laravel-doctrine/fluent which basically is a mapping driver that allows you to manage your mappings in an Object Oriented approach. And there are other tools:
http://crud-admin-generator.com/
http://crudkit.com/
http://www.grocerycrud.com/
which are maybe better for that, I don't know.
But again, please don't do that. Do not allow the customer to modify the database schema or give them e.g. a phpMyAdmin which was designed for that.

Add column to aspnetusers with database first

I have found many tutorials for adding columns to the Identity tables (which I have successfully moved to the application database) with database migrations however my understanding is this is not applicable in database fist projects. So...how do I add columns to the aspnetusers table in a database first project?
I would like to ad a bit type column called Is RegComplete which is initially set to 0 then at some point when the user has completed some more tasks then set to 1.
OK, I've cracked it! Firstly I didn't realise that although I have moved the Identity tables to the Application database there is still two Database Contexts, one for the application tables which are DB First, and the other for the Identities tables.
I was able to enable migrations and add the column using code first and migrate then update the database. The new column is now available in the controller.
I found this tutorial which helped me: http://blogs.msdn.com/b/webdev/archive/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates.aspx
The easiest solution:
Add columns into AspNetUsers table
Add properties into IdentityModels.cs class (Check attachment)
Add same properties into AccountViewModels.cs\RegisterViewModel class
Compile and it will work.
Attachment
(VS 2017, MVC5)

To fill up asp.net membership

I believe I want to do a update query.
I've found a tutorial that introduces me to ASP.Net membership where I can use an Access provider to fill my database needs. However, I have an existing Access database of customers, but I do not know how to copy this existing database into the new ASPNetDB.mdb. It's identical to the SQL provider as far as I know.
Every table is related to each other so I cannot enter new records. I've wanted to append the UserName column, the passwords, email's, and a new field to the new ASPNetDB.mdb. How would I go about doing this?
So instead of having to copy records from one database to another database why don't you just create a custom membership provider and use the same existing database.
Basically you create a class that inherits from the MembershipProvider class and you implement all the methods from the MembershipProvider class. I.E. ChangePassword, CreateUser, DeleteUser, etc... In your implementation you write custom code to access the tables that already exist.
This way you can keep your current database and still use ASP.NET membership.
Here is an MSDN article with a sample implementation.
Sample Membership Implementation
As suggested, if the table structures ARE the same, then why not just make a copy of the original database and re-name to the same as your ASPNetDB.mdb.
If you're looking to import older data, then again simple open ASPNetDB.mdb with Access and import the data + tables from the older database. Access can and WILL import the tables and WILL ALSO BRING IN related data tables. This will create new local tables, but then again you stating they are the same. (so delete the existing tables in ASPNetDB and import the other ones).
You can ALSO import the table data into existing tables if they are empty. So assuming empty tables, then a compact + repair will re-set auto numbers, and then you can link to the older database and use append quires. I would only do this if a few tables. You have to import the "parent" tables first if referential integrity is enforced as it makes little sense to add child records first!
However I fail to see why not just making a whole copy of the older existing database and re-naming it as ASPNetDB would not work if your claim of the tables being the same in both.

Adding table from another database to ASP.NET Dynamic Data + Entity Framework

I have a table in another database I would like to scaffold via ASP.NET Dynamic Data and incorporate into my existing Entity Model - is there anyway to do this? (eg using a view or other mechanism or customize the view, edit or insert operations via ad-hoc SQL or stored procedures?)
I don't want to replicate the entire DynamicData sub-folder structure and create another entity model for just one table
I was able to solve this by manually creating an entity in the SSDL and CSDL sections of the .edmx file by using a DefiningQuery and then defining the EntitySets for my entity class
I also added insert / update / delete Function elements to the SSDL with inline SQL using the CommandText property
At this point I had enough to let the Designer map the CRUD methods to these inline SQL functions I defined
It's a little tricky but it works and the general approach opens up many possibilities I had not thought about

MVC3 Entity Framework using default membership relationships

I want to create a relationship between a custom table (Websites) and the default aspnet tables related to Users.
I'm using code-first so for most FK relationships I would just do
public ModelName ModelName { get; set; }
With this, EF will automatically create the FK relationships. Very easy.
What's confusing is the most effective way to hook into the aspnet users/membership table. Do I create a new model Users that acts as an interface so that I can implement custom user code?
Is there a best way to do this that fits well into EF best practices? I basically just want to relate a user to the Websites table/model so that EF can do its thing.
"Do I create a new model Users that acts as an interface so that I can implement custom user code?"
If you want flexibility, I would say this is the way to go. This way it would be easier if you wanted to change to some sort of different Authentication DB structure in the future.
For example, have an "AppUser" Entity where the corresponding table has a foreign key to the "UserID" column of the aspnet_Membership table. This way you can simply add properties to your "AppUser" Entity instead of trying to change the MS table structure (which can be a real pain). You can still interact with the built-in MS Membership classes and functions from your MVC project using something like the MvcMembership starter Kit DLL's.
https://github.com/TroyGoode/MembershipStarterKit
Hope this helps!
This has few preconditions:
ASP.NET tables must be in the same database as your own tables
Previous precondition means that you must either create your database and tables manually (without automatic code-first generation) or you must use some custom initializer which will add non mapped ASP.NET tables as part of database recreation
If you want your model class to have relation with ASP.NET table you must model ASP.NET table as another entity. I'm not sure if you can use ASP.NET classes for that because for example MembershipUser doesn't have parameterless public constructor which is required for EF. So you will most probably need to create duplicate classes and their mappings and use these classes when referencing ASP.NET entities.

Resources