How to change table name using database first Entity Framework - c#

This is similar to this question but with using database first entity framework instead of code first:
How can I change the table names when using Visual Studio 2013 ASP.NET Identity?
In the code first approach you can override OnModelCreating and do something like this so that the user info is saved in MyUsers table instead of the default AspNetUsers:
modelBuilder.Entity<IdentityUser>().ToTable("MyUsers")
In the database first approach I have manually created the MyUsers table but because OnModelCreating does not get called I don't know how to configure the data to be saved into my new table?

You can follow the Code First approach an when overriding the OnModelCreating add the line:
System.Data.Entity.Database.SetInitializer<ApplicationDbContext>(null);
The line above will link the AspNetIdentity entities to your tables without re-creating the tables.
Code Example:
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUserRole>().ToTable("UserRoles");
modelBuilder.Entity<ApplicationUserLogin>().ToTable("UserLogins");
modelBuilder.Entity<ApplicationUserClaim>().ToTable("UserClaims");
modelBuilder.Entity<ApplicationRole>().ToTable("Roles");
System.Data.Entity.Database.SetInitializer<ApplicationDbContext>(null);
}

Related

Prevent table generation for a specific entity in EF6

How do I disable table generation for a specific entity when my DB context is initialized?
public class MyDbContext : DbContext {
public DbSet<MyEntity> MyEntity{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Ignore<MyEntity>();
base.OnModelCreating(modelBuilder);
}
}
This code helps but it excludes the entity completely and I still need to query it.
Without getting into too much detail, EF compares generated code your DB structure to the previous generated code when looking at migrations: it doesn't actually compare against the raw DB every time.
You should be able to bypass it wanting to create a table by creating a new migration, deleting/commenting out the table create code in UP and table remove code in DOWN, and apply the empty migration. It'll still have the view in the generated code, so it won't try to add it again.
You can create an empty migration as the first migration with the -IgnoreChanges flag to allow Entity Framework to get a snapshot of the existing database. For example:
Add-Migration InitialMigration -IgnoreChanges
This will map your entity to already existing table or a view in your case
modelBuilder.Entity<entityname>().ToTable("Tablename");
or using data annotations like this
[Table("tablename")]
public class ClassName {
....
}

Entity Framework Database First: connect to a particular database schema in runtime mode

We were recommended (by Microsoft specialists) to use database schemas inside a single db instead of separate databases for each customer of our service.
We are currently using Database first approach.
User story: when I log in as a guy from company 1, on page "warehouses I get info from table u1.Warehouses. Company 2 - u2.Warehouses and so on.
Question: by having schema name for a particular user, how can we establish connection to that_schema_name.Table_name in runtime mode using Entity Framework?
Thanks!
Depending of the user that is logged and his membership to roles, company, or whatever you define in your application, you can conditionally set the schema. Bellow I provided the sample with If control flow construction and IsInRole method from CurrentPrincipal, obviously it may not be your final solution but should put you in track :
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
if ( Thread.CurrentPrincipal.IsInRole("Foo") )
modelBuilder.HasDefaultSchema("that_schema_name");
else
modelBuilder.HasDefaultSchema("other_schema_name");
...
}

EF6 dynamically changing a Schema

I have a database that contains an unknown number of schemas, each schema has the exact same tables.
Is there anyway to change the schema at runtime when creating a new instance dbContext? I know it's possible to change connection strings at runtime, however the schema names is stored in another database as a table of configurations.
I saw that in EF6 you can set a defaultSchema when overriding OnModelCreating however I am not too sure if this is guaranteed to run everytime I use using (DatabaseContext db = new DatabaseContext()){}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(SchemaName);
}

c# EF generating wrong table names on SQL Compact

Using latest EF and EF SQL Compact (6.1.1) with SQL (4.0)....
Noticed via Linqpad that the table names generated through my initializer (DropCreateDatabaseAlways) are different than what I have specified in the Table attribute. When developing I am creating an embedded database for test purposes but other environment the database will be legacy which means the table names must match then.
If I have [Table("p_Brand_Visited")] on an entity the generated table name is P_Brand_Visiteds. The first letter is capitalized and the name is made plural. Not sure why the Table attribute is not respected. Maybe a SqlCe issue?
Tried via the OnModelCreating event to remove pluralizing:
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
No effect. Tried to set the table name:
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<BrandVisited>().ToTable("p_Brand_Visited");
}
No effect. Any other suggestions? Ways to debug?
This was a problem with Linqpad and the plural options. Once these were disabled everything worked fine.

Entity Framework 5 rc Code First Specifying Schema to create tables under?

Using EF 5 RC what is the proper way to specify what schema tables are created under while using the Code First process?
I have tried:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Metric>().ToTable("Metrics", "Dashboard");
}
But the SQL script created doesn't recognize the schema and makes all the tables under the dbo schema.
TIA
J
If you right click on the EDMX designer surface and go to properties you can set the schema for that diagram. So if you want to put different entities/tables in different schemas you have to keep them on seperate design surfaces.

Categories

Resources