1
votes

I am trying to implement Database first approach using Entity Framework 5.0 but somehow I am not getting it right. I have the following doubts which needs to be cleared.

1.After adding the Ado.Net Entity Data Model a DBContext class 'Model.Context.cs' gets auto-created in the folder under "Model.Context.tt". Do i need to add DbContext Generator again?(I have found this recommended by others but i could not make out why!)

2.How to scaffold a controller from the edmx files? Suppose I have an entity, say A (which I want to scaffold to a controller),having one to many relationship with entity B, where will I define this relationship? In the auto-generated model classes from edmx files or do i create classes A & B and define again and then scaffold Model A?

Any help will be very much appreciated. Thank you

1
With Database First, you just set the relations between the tables in the database and the EF will generate all the rest work. Scaffolding will see the realations. Just Add new Controller with scaffolding set the Model class and the Datacontext generated by VS from the db.jannagy02
Thank you for the reply.Yes, I have tried scaffolding the model class with the DataContext class as is generated by VS but the relationship keys do not hold as I have mentioned above. I will try and share the code. Thanks.Aritra B

1 Answers

1
votes

Abhatt:

  1. What t4 templates do is generating classes for you and you need to keep them, unless you decide to use another t4 template. For instance, you may want to design you database but after that decide to use code first to take advantage of code first approach, in that case after designing the database you will add another t4 template named "EF 5.x DbContext Fluent Generator for C#" and that template creates the poco class and all mappings for you.

  2. Whenever you are adding a controller mvc uses scaffolding to create controller's methods and views. However, if you want to have more control on how to generate them, you may install MVCScaffolding from package manager console. Having MVCScaffolding installed, you will be able to customize t4 templates. For more info check out MVC Scaffolding project on CodePlex: http://mvcscaffolding.codeplex.com/ also there is another good one: http://www.codeproject.com/Articles/468777/Code-First-with-Entity-Framework-5-using-MVC4-and