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 {
....
}
Related
I'm new, excuse my ignorance.
I have this class:
public class Genre
{
public int Id { get; set; }
[Required]
[StringLength(40)]
[Index(IsUnique = true)] //-----------------------> new change
public string Name{ get; set; }
}
In my first migration called Initial, I forgot the [Index(IsUnique = true)] attribute which makes the Name field unique. So now I want to update my database model for this change to take effect.
I installed the package using System.ComponentModel.DataAnnotations.Schema; to be able to use the unique property.
The commands I ran were:
EntityFrameworkCore\Add-Migration Initial
EntityFrameworkCore\update-database
Apparently I can't do something like:
EntityFrameworkCore\Add-Migration change_attribute_name
EntityFrameworkCore\update-database
to update the database model and that I updated the unique attribute on the Name field which is what I am doing.
I would like to update the model of my database, with the new changes. How can I do it? and what is the best way?
Note: my SQL Server database has no data yet.
Maybe I've been doing fine, you know why the unique attribute is not added in my database model?
(In Spanish Genero=Genre and Nombre=Name)
EDIT
In EF core, you need to apply the unique index in the following way using Fluent API in your ApplicationDbContext.cs file:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Genre>()
.HasIndex(u => u.Name)
.IsUnique();
}
Since as you mentioned, you do not have any data in the database yet, you can revert all your applied migration by using
Update-Database -Migration 0
the -Migration 0 indicates that you want to un-apply all the migrations.
Then you can remove your generated migration using
Remove-Migration
And finally, add migration again using new changes by
Add-Migration Initial
Change the model an try adding migration
Add migration yourmigration name
And then run
Update database
Command this will work for you for sure
I have a database with two tables :
Employee Salary
======== ================
Id Name Id EmpId Salary
and of course there is a class for each table to implement code first migration.
Is there any way to copy the database tables from the source database to another database and change the names of the tables using EF code-first?
PS: The target for this method is to create default database with default structure and when new client register create his own tables in existing database with new name
The easiest thing to do is to run code first against the database you are trying to copy the tables from (Add-> New Item -> Data -> ADO.NET Entity Data Model -> Code First from database.) Check off the tables you want to import. When you are done doing that delete the Entity DBContext and the connection string in your web.config. This will create all the models from the db you are trying to create. Add them to your model; Done.
public DbSet<StudentsModel> MyNewTable{ get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
modelBuilder.Entity<MyNewTable>().ToTable("MyTable");
In this case Entity framework layer code will differ from client to client?
Since you will have some more table on one client than another one.
You can change the name by
modelBuilder.Entity().ToTable("mytesttablename"); fluent API
OR table attribute
[Table("mytesttablename")]
public class test
{
}
etc
I am using Entity Framework Code First in my project, and I did something quite silly I can't fix. I have renamed a table in SQL Server Management Studio, and then deleted it there. I then recreated the correct table (just an 's' that wasn't supposed to be here). Now it's not here anymore and I keep getting exceptions in my queries since EF looks for a table that does not exist anymore (even though I renamed it everywhere!). Now my table is called RelImpUser and it used to be RelImpUsers.
So I have tried recreating the table in SQL Server, then making a migration with :
public override void Down()
{
DropTable("dbo.RelImpUsers");
}
But this does not delete my table. And everytime I execute a query, it looks in RelImpUsers, it does not go for RelImpUser which is the only name I put in my code. Any ideas how to fix this? I can add some code if you want, I just felt it doesn't help much here.
Edit 1: It might have to do with the pluralization of my tables. So all my tables all had plural names, but the new one doesn't, BUT EF still pluralizes because I checked the option when creating DB Code First.
Thanks!
Code First uses its models to build the queries. You will need to annotate your RelImpUser class (or add comparable fluent code):
using System.ComponentModel.DataAnnotations.Schema;
[Table("RelImpUser")]
public class RelImpUser
{
public int RelImpID { get; set; }
public string Field1{ get; set; }
...
}
Fluent equivalent:
modelBuilder.Entity<RelImpUser>().ToTable("RelImpUser");
If you don't want pluralized names, you can turn that convention off:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
I am implementing a MVC-Webapplication with ASP.NET Core (RC2) and as ORM Entity Framework Core. Since I already got a database design, I have to create the entity models by the Scaffold-DBContext command.
This works fine. Now, I want to add some annotations to the generated entities in order to add validations. For example MaximumLength:
public class Blog
{
public int BlogId { get; set; }
[MaxLength(500)]
public string Url { get; set; }
}
If there are some database changes, I have to use the scaffold command again. But this results to the loss of some additional annotations. How can I update the entity models without loosing them? According to asp.net page or from this topic, It seems to be possible with EF6. Is there a similar way to achieve this with EF7/Core?
Yes,you can.You have to use Fluent API instead of Data Annotations.
Here is your example using Fluent API
public partial class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.HasMaxLength(500);
}
}
OP's feedback
But the Database context class will be also generated. This means, If
I use the command again, it will replace the old database context.
My suggestion :
You can use partial class here.keep your custom implementation on that file.Those pieces of custom code won't get overwritten when you re-generate the code.
OP's feedback :
I could solve it with partial classes BUT after generating the
entities, you have to go through all entities and delete all
duplicated properties. Still not quite that what I am looking for,
because you still have to modify the entities.
My suggestion :
You don't need to delete any duplicate mappings. B'cos EF gives precedence to the Fluent API.It doesn't matter what ever the mapping has done by the code regeneration automatically. You can overridden those using Fluent API.That is the power of Fluent API.You can also use DataAnnotation and Fluent API at the same time. But code-First gives precedence to Fluent API > data annotations > default conventions.
I'm using EF 4.3 code-first with an Oracle database. One weird thing about the database is that it automatically makes table and column names ALL CAPS. My domain properties are in PascalCase. Unfortunately, EF doesn't know to capitalize column names, so my queries don't work. I have hundreds of properties on several classes that should map to oracle columns. I would really rather not manually code all those mappings. Is there a way to use a convention to capitalize column names?
SUMMARY:
I need for Entity Framework to use ALL CAPS for all column names. How can I do that?
Haven't tried this, but what about something like this:
public class SomeEntities : DbContext
{
public DbSet<Entity> Entities { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Configure Code First to ignore ColumnTypeCasing convention
modelBuilder.Conventions.Remove<ColumnTypeCasingConvention>();
}
}