I am new to Entity Framework. I have created an EF Model and successfully added some tables and relation. Then I Clicked Generate Database from Model and My DB has been updated. Then I renamed some columns and I don't know how to revert or apply the changes. And Update Model from database does not seems to work because the columns names are different yet.
I need to graphically sync DB with Model. I prefer the model data rather than db data.
Thanks in advance.
You might want to look into the Code-First approach of Entity Framework. Using that approach you'll define your model in your code, and when changing anything you can create a Migration which allows you to up- and down-grade the DB to a specific version from the package manager console (or just create the respective SQL scripts).
For more information on this subject please see this article on MSDN
Note that you can also reverse engineer the code first model from an existing database (see 3. Reverse Engineer Model in this MSDN article), and then enable migrations for that model (see Step 2: Enable Migrations in this MSDN article)
What I do when I make "updates" is do it on both sides manually, in db and then in model (by right click properties) if the change is small. If adding a "new" table I drag it over to model from db server connections panel.
The alternative I've seen others prefer to use in this cases is to stay away from Entity Framework and use Dapper where you pass queries to it and it handles the rest.
Dapper (Wins!) vs Entity Framework vs ADO.NET Performance Benchmarking
Related
Assumptions
Using EF 6.1, MVC 5, VS 2013, C#
I have an existing database model designed in Toad DM for SQL Server and it's very important keep it always updated
Steps and Notes
Using ADO.NET Entity Data Model I chose Code First from Database (new feature in EF 6.1) to generate the models. Note: Model classes and DbContext class generated successfuly but NO .edmx or .tt file was generated.
Next I added a new scaffold item: MVC 5 Controllers with views, using Entity Framework. Note: Success, controllers and views generated
Question
From now on I don't want to use Code First to update my database. Instead I want the models to be updated based on database changes. What to do next? If I don't have an edmx file will I not be able to update my model classes from the database?
The Entity Data Model Wizard's Code First from Database does an excellent job creating your entity classes, as if they were created in the Code First style. What you are asking is if there is any way to keep these classes up-to-date as your database changes, similar to the EDMX style "Update Model From Database". From what I've researched this is not possible using the built-in tooling. However, here is one workaround that I've found useful:
Let's say I have database with a product table and customer table. Originally I created a StoreDBContext class, and selected product as one of my objects. Now I want to add the customer table as a new entity to the existing context. Here's how to do this using the Code First Wizard:
Create a new Entity Data Model, call it StoreDBContextTemp or whatever
Choose the code first from database wizard option
Select customer as an object to add (just customer) & complete the wizard
Open the newly created context file, StoreDBContextTemp.cs, and copy the virtual properties of your newly added entities:
public virtual DbSet<Customer> Customers {get; set;}
Paste these new properties into your Original StoreDBContext.cs dbcontext class.
Delete StoreDBContextTemp.cs, and remove the connection string for StoreDBContextTemp in app.config/web.confg etc.
You can now use Customer on the StoreDBContext class
If you add or remove tables you will need to manually adjust fields, but at least you won't need to hand write dozens of properties each time a new table is added to the model.
One more option is just delete the auto generated classes from the project and once again generate them.
While following this approach only thing we need to make sure that is we should give the same name for the data model(class name which inherits from DbContext ) as the previous one.Data model name is highlighted in below snap
Three things.
There's no .edmx when you use Code First.
If you use Code First Migrations you would have to write first the code and after that migrate the changes to database. This helps you to have much more organized you code with no generated code which is an advantage.
There's a plugin in Visual Studio for doing contrary. Entity Framework PowerTools allows you to select the database and map it to objects.
https://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d
The best solution to me is deleting the model and recreate updated one with the same name, keeping in mind two points:
Personal extension methods implemented for the model;
Possible manual relationships between tables added to the model because of not setted up in the phisical db.
My personal solution:
Move all extension methods to another partial class that won't be overrided;
Insert all added properties of an entity to another partial class;
Keep track of all manual relationships in an help file, so you can add them again being sure not to loose anything;
Delete the old model and recreate one new with the same name and update it with the manual relationships of point 3.
I have used EntitFramework before to do codefirst with MVC; however, I have never reverse engineered an existing database to get my models.
So what I'd like to do is reverse engineer the existing DB then switch to codefirst so that changes made to the models will be reflected in the database automagically by the Entity Framework gods. How would I do this, specifically the reverse engineer then the switch to codefirst? Please have mercy if this is poorly worded or w/e I'm very new to MVC still.
It basically boils down to using tools to autogenerate the POCO classes that represent your domain, then using those classes as the basis for EF Code First and future migrations.
Here's a msdn article outlining the process
Code First to an Existing Database
You can reverse an existing Database by creating an Entity Data Model.
Check the following link. Here is described step by step the how to reverse a database to a CodeFirst approach with all of the navigation properties and required relationships. This scenario is also very useful for those entity relations that CodeFirst cannot resolve by its own and the configuration in not very intuitive.
Reverse from ModelFirst to CodeFirst
We are upgrading an old VB6 application which sits on a SQL Server 2005 database, to an Entity Framework solution. The database remains the same, except - we're adding a new table. Is it possible with Entity Framework, to maintain the existing structure, when it gets installed on a client PC - and just add one new table?
Is this how Code First will work? Can I be 100% certain that no other tables will be modified?
i don't think, the effort is worth it to switch to code-first if you have an existing database and want to add only one table.
it is possible to map code-first classes to an existing database (reverse engineer code first). actually, i'm not very experienced with that workflow, but i know you can. You have to deal with a lot of manual mapping (with DataAnnotations or Fluent API), so in your case i would recommend to use the Entity Framework Database First workflow, since adding a single table saves you a lot of work.
this link has some useful information: Arthur Vickers Blog - Don't use Code first by mistake
You have two options, use a database editor such as SQL management studio to create the table which you can then map to a ef entity, or use migrations for ef which will let you update your database via ef.
Take a look at the migrations tutorial here: http://msdn.microsoft.com/en-gb/data/jj591621
I am using the database first approach, since a database developing team is doing the changes I require in the database on the SQL server for me.
Hence, I have to update the EDMX whenever the schema in the database changes.
Note: Changing one single table directly does not work for me, because VS doesn't always detect the changes right (for this issue, here are some details in SO if you're interested).
Hence, I am using the following workaround (regenerating all the tables):
In VS 2012, open the EDMX file by double-clicking on it. The graphic representation of the tables is shown.
Left-Click into the EDMX designer, then select all tables by pressing CTRL+A. Then, remove them by pressing DEL.
Right-Click into the EDMX designer and select "Update Model from Database ..." in the context menu.
The Update Wizard opens. In the "Add" tab, check "Tables", and depending on the requirements, check "Pluralize or singularize generated object names", "Include foreign key columns in the model" and optionally "Import selected stored procedures and functions into the entity model". Usually, I am using the "Pluralize..." and "Include foreign key columns..." options.
Click Finish. Now Save by pressing Ctrl+S.
That workaround works fine for me, and requires just a minute to update the model reliably.
Using the code-first approach available in the new 4.1 RC.
Is there any way to persist the current data stored in a database when the mode changes? The database is created by the entity framework, and usually the database is dropped and recreated on model changes.
Obviously as soon as the model is changed it will not be possible to use the context object to connect to the database to retrieve the data, so what are the options?
Code first doesn't support database migration / evolution yet. If you want to do incremental DB development use model first (EDMX) with DbContext Generator T4 template and Entity designer database generation pack which is able to create diff. scripts from the model.
From Scott Gu:
Importantly, though, the auto-create
database option is just an option – it
is definitely not required. If you
point your connection-string at an
existing database then EF “code first”
will not try and create one
automatically. The auto-recreate
option also won’t be enabled unless
you explicitly want EF to do this – so
you don’t need to worry about it
dropping and recreating your database
unless you’ve explicitly indicated you
want it to do so.
Background:
I started to create logical database model for ASP.NET MVC web site. I used visual designer for Entity framework that ships with VS because I have used it before.
But now I already have 33 classes and I'm not finished (including quite some inheritance and a lot of associations). I'm afraid that it would be too complicated and time consuming for me to manually set all the table mappings and than generate database tables. I've no experience with it - I've done it the other way: classes from database tables and it took me a lot of time to get it work in a smaller project.
Question:
How can I easily and quickly create database tables for logical model (class diagram) in .NET / VS ? It would be great if it was possible automatically. I have never worked with LinqToSQL visual designer and it seems to be no reference on the web on how to create database tables from LinqToSQL classes. Is it possible at all ? If not is there any way to create database tables with Entity framework automatically - without having to specify table mappings ?
And one side question: if I used LinqToSQL classes are that going to commit changes to database every time I change properties ? Or is some caching taking place there ?
Entity framework has a concept called "Model First", which generates the database model from you model, hence the name.
You can read about that here: http://msdn.microsoft.com/en-us/data/ff830362
However, my personal favourite when it comes to Object Relational Mappers is NHibernate with the addition Fluent NHibernate. They have a concept where you work with your domain model rather than you data model and you use conventions to control your mappings. It's pretty neat. You can get started with some pretty good examples by looking at this code here: https://github.com/sharparchitecture/Northwind/tree/master/app
Linq2Sql is too limited for the case you are talking about. And it has no capability to generate data models from code. In fact, Linq2Sql works the other way around - it generates a set of classes from your data model, much like Entity Framework also can do.
Neither Linq 2 SQL or Entity Framework commit anything until you explicitly choose to do so. They both have a notion of a object context which keeps track of all changes made. When you call "Save", they transform those changes into SQL which is then executed in the database.
Like MikeEast, I've had a very good experience with Fluent NHibernate.
On my project, I use the Automapping feature, which allows me to change my data model almost at will, and the database schema automagically gets updated.
No SQL, no worrying about foreign keys, etc, etc, etc - I love it!
Fluent NHibernate Automapping
Finally I have sticked with Entity framework - tables generating is really plainless once I learnt how to deal with database connections...