I have 2 table which I'm trying to access in MVC, one called Employees and one called Accountable. This is my code: -
public class dbEntity: DbContext
{
public dbEntity(): base("name=dbEntity") {}
public DbSet<Accountable> Accountable { get; set; }
public DbSet<Employees> Employees { get; set; }
}
The problem is the code complains that it can't find the table 'Accountables', I know I can add this line: -
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); }
But then the code complains that it can't find 'Employee'. At the moment it is not practical to rename the tables, is there another way around it?
Thanks
Add a data annotation of your table's name in the database to your context class.
[Table("TableName")]
Related
I'm using Entity Framework to insert data into 2 different databases. There are a few columns that are present in one of the databases but not the other. Their data types are not nullable (int and float).
I don't use these columns (when they are present) in my code. Meaning I only insert 0 as the data for them but I can't send null obviously.
Is there a way for me to insert data with ease without creating 2 different versions of my app for these? Ideally I'd like to just have one model with something like an attribute that says insert 0 in this column if it's available.
If your application runs only against one database, then you can just use an IF statement in your OnModelCreating that uses the Fluent API to .Ignore() the missing properties.
public class MyDbContextWithMissingColumns: MyDbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (myConfig.UseDatabaseWithoutSomeProperties)
{
modelBuilder.Entity<Foo>().Ignore(f => f.SomeProperty);
}
base.OnModelCreating(modelBuilder);
}
}
If a single instance of your application connects to both databases, then you have to use separate DbContext subtype, as OnModelCreating only runs for the first instance of a DbContext type in an AppDomain.
EG:
public class MyDbContextWithMissingColumns: MyDbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Foo>().Ignore(f => f.SomeProperty);
base.OnModelCreating(modelBuilder);
}
}
In the repository for the database with the restricted fields create the entity:
public class MyClass
{
int MyCommonClassID {get; set;}
string Name {get; set;}
[NotMapped]
string PhoneNumber {get; set;}
}
Where the attribute [NotMapped]. is used that field will not appear in the database but you can use it everywhere else. That wat you determine what gets written at the lowest level and your application doesn't care.
I have a site. using COde first. My add-migration command producted following code.
public partial class StudentEntity : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Student",
c => new
{
id = c.Int( nullable: false, identity: true),
name = c.String(),
})
.PrimaryKey(t => t.id);
}
Now I want to deploy my site so when site runs the first time I want the Student table to get generated in DB(SQL server).
Right now when I run the site it does not create any table. How can I do this? I dont want any seed data to initialize with
My db context class
public partial class flagen:DbContext
{
public flagen() : base("name=cf2")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
//old entity
public virtual DbSet<flag> flags { get; set; }
//new entity
public virtual DbSet<Student> students { get; set; }
}
Then I tried to use Context so table get created. It throws error "The model backing the 'flagen' context has changed since the database was created. Consider using Code First Migrations to update the database "
The I added following two lines to dbcontext class
Database.SetInitializer<flagen>(null);
base.OnModelCreating(modelBuilder);
now it says "invalid object name students"
any solution that works?
One solution could be to define a Initializer that will migrate your database to last existing migration you added. Therefore all tables will be created and the Seed method of the Configuration will be executed too - you could use it for seeding data.
With the following example your database will be updated to last existing migration (and therefore creates all tables) on first initialization of the data context. (var dbContext = new MyDatabaseContext())
In my opinion a much cleaner way than to use AutomaticMigrationsEnabled = true that you could check out too. ;)
As mentioned here is an example that will use the MigrateDatabaseToLatestVersion initializer with the defined behavior.
public partial class MyDatabaseContext : DbContext
{
public virtual DbSet<Student> students { get; set; }
public MyDatabaseContext() : base("MyDatabaseContextConnectionString")
{
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDatabaseContext, Migrations.Configuration>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// here we want to define the entities structure
}
}
You will find some more information about the initializer itself here (MSDN
- MigrateDatabaseToLatestVersion) and here (Entity Framework Tutorial - Code-First Tutorials - Automated Migration) is another example with some more background information and examples.
The answer of this question is to use T4 templates. After searching the web I got the answer that nobody could on SO. Shame...
https://archive.codeplex.com/?p=t4dacfx2tsql
I have a project built using EF code first. It also uses forms authentication. Until recently the membership database and the application database were being developed separately, but I want to combine them into one database for simplicity.
One of the classes in my code first model is called "Application" so the EF-generated table is called "Applications" which conflicts with a membership table of the same name. This is an example of my current context:
public partial class ExampleContext : DbContext
{
public DbSet<Application> Applications { get; set; }
public DbSet<Status> StatusTypes { get; set; } // notice the name of the property vs the name of the class
}
I thought the table names were based on the names of the properties in the context, because it was generating a table named StatusTypes for all of the Status objects. But if I rename the Applications property to something like MyApplications it is still generating a table named Applications. So clearly it's not just the name of the property and I'm missing something.
My question: how do I get EF to name this table differently?
Couldn't you use the configuration class to do something like this:
public class ApplicationConfiguration : EntityTypeConfiguration<Application>
{
public ClientConfiguration()
{
ToTable("SpecialApplication");
}
}
Then in your context override OnModelCreating:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ApplicationConfiguration());
}
This should then force your table to be named SpecialApplication and avoid the conflict
By default, Entity framework code first will generate pluralized names for tables when it builds the db from the model classes. You can override the OnModelCreating method of your db context class specify a different name for the table.
public class YourDBCOntext:DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Applications>().ToTable("MYApplications");
}
}
You can do this globally also so that none of the tables will have pluralized names.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTaleNameConvention>();
}
}
I just renamed the class and it worked. Easiest solution for now.
I would like to mention that i am new to EF.
I am creating the Data Access library with EF 4.1.
For each Entity I have two tables for translation target.
ex : Events ==> Event_ar for Arabic and Event_en for English.
First Problem : I have an error if i write two DbSets of same Entity Type
so I did this work around which is absolutely not nice :
public class Event_en : Event { }
public class Event_ar : Event { }
public class DB : DbContext
{
public DbSet<Event_ar> Events_ar { get; set; }
public DbSet<Event_en> Events_en { get; set; }
}
I would like to know if there is a solution for it?
Second one
The Entity should be same name as a table, otherwise i have an error.
Ex : "dbo.Event_ar" should have a POCO "Event_ar"
It should be the name of the property that has the same name of the table.
Here : dbo.Events_ar ==> POCO "Events_ar"
Why I can't manipulate the names? Any solution?
I'm not sure if your solution is going in the right direction. It doesn't feel right to have a table for every language - you could simply add another column to the event table that specifies what the language is?
The you could use this column to retrieve the row with the desired language.
About tables and POCO entity names, you can override the table the entity is mapped to either through the use of a System.ComponentModel.TableAttribute at the class elvel, but to maintain POCO-ness I like to use EntityTypeConfiguration classes and specify the table name.
for example:
public class CurrencyConfiguration : EntityTypeConfiguration<Currency>
{
public CurrencyConfiguration()
{
this.ToTable("Conv", "Ref");
}
}
Then you add it to the model builder in the OnModelCreating override method on the DbContext.
public class MyContext : DbContext
{
public DbSet<Currency> Currencies { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CurrencyConfiguration());
}
}
How do I make non persisted properties using codefirst EF4?
MS says there is a StoreIgnore Attribute, but I cannot find it.
http://blogs.msdn.com/b/efdesign/archive/2010/03/30/data-annotations-in-the-entity-framework-and-code-first.aspx
Is there a way to set this up using EntityConfiguration?
In EF Code-First CTP5, you can use the [NotMapped] annotation.
using System.ComponentModel.DataAnnotations;
public class Song
{
public int Id { get; set; }
public string Title { get; set; }
[NotMapped]
public int Track { get; set; }
Currently, I know of two ways to do it.
Add the 'dynamic' keyword to the property, which stops the mapper persisting it:
private Gender gender;
public dynamic Gender
{
get { return gender; }
set { gender = value; }
}
Override OnModelCreating in DBContext and remap the whole type, omitting the properties you don't want to persist:
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Person>().MapSingleType(p => new { p.FirstName, ... });
}
Using method 2, if the EF team introduce Ignore, you will be able to easily change the code to:
modelBuilder.Entity<Person>().Property(p => p.IgnoreThis).Ignore();
If you don't want to use Annotations, you can use the Fluent API. Override the OnModelCreating and use DbModelBuilder's Ignore() method. Supposing you have a 'Song' entity:
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Song>().Ignore(p => p.PropToIgnore);
}
}
You can also use EntityTypeConfiguration to move configurations to separate classes for better manageability:
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new SongConfiguration());
}
}
public class SongConfiguration : EntityTypeConfiguration<Song>
{
public SongConfiguration()
{
Ignore(p => p.PropToIgnore);
}
}
I'm not sure if this is available yet.
On this MSDN page the Ignore Attribute and API are described but below, in the comments, somebody writes on 4 june 2010:
You will be able to ignore properties in the next Code First release,
Add
using System.ComponentModel.DataAnnotations.Schema
to the model class. (Must include "SCHEMA")
Add [NotMapped] data annotation to the field(s) you want to keep from persisting (ie. not save to database).
This will prevent them from being added as a column to the table in the db.
Please note - previous answers may have included these bits, but they did not have the full "using" clause. They merely left off "schema" - under which the NotMapped attribute is defined.