1

I have a (strange) situation. I am using Entity Framework Code First but I have to attach to an existing Database.

I do not have to map every single table of the database in my object model. So I would like to migrate single Tables, whenever I need it. I try to explain better. My database have about 100 tables, but I need to map in my model just 3 or 4. I have created my classes in c# and now I would like to map this classes with the tables I need.

Is it possible to do it? Do I have to do a migration?

UPDATE Here my class:

public class PricePlan { public Guid Id { get; set; } public String Name { get; set; } public Double ActivationPrice { get; set; } } 

Here the context:

public class PublicAreaContext : DbContext { public DbSet<PricePlan> PricePlans { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<PricePlan>() .HasKey(pp => new { pp.Id }); base.OnModelCreating(modelBuilder); } } 

Here the table:

ALTER TABLE [dbo].[PricePlan]( [Id] [uniqueidentifier] NOT NULL, [Name] [varchar](50) NULL, [ActivationPrice] [decimal](5, 2) NULL, ... //Other columns CONSTRAINT [PK_Price_Plans] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

1 Answer 1

2

possible: yes

migration: no. If you need migration you may have problem as in this case you haven't the __migrationHistory table (as the db is "existing" by opposite to "created by EF").

But the answer is definitively yes.

Create your classes, create a DbContext comprising DbSet, "et voilà".

Sign up to request clarification or add additional context in comments.

5 Comments

It's not enough... When I try to do an insert to the table of database, I obtain this message: The model backing the 'PublicAreaContext' context has changed since the database was created. Consider using Code First Migrations to update the database.. Give me 2 minutes and I update the question
do you have a __migrationHistory table in your database ?
that means that the database is not "existing". Don't you have access to the context class corresponding to the Db ? Otherwise you may use Database.SetInitializer<MyContext>(null); stackoverflow.com/questions/10623260/…
Strange, I have solved deleting the __migrationHistory and launching the following command: Update-Database -verbose -StartUpProjectName MyProject int the Package Manager Console
Not strange: DANGEROUS. There is an historical context accessing the database (the one which created the __migrationHistory table). Now this context, and the app depending on it may become instable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.