Prevent EF6 from generate navigation properties - entity-framework-6

I've recently started to use EF6 and i'm building a couple of T4 templates to generate some code automatically (on VS2012).
I'm generating my model from the database and this process creates all the associations automatically based on the DB ForeignKeys. And generates too a "Navigation Property" for that field in Associations/FK.
I want to get a "Flat Version" of my entities without navigation properties. Just a class with properties corresponding to table columns.
Is there any way to "Generate Model from Database" and get this? i've tried to update model with the option "Include foreign key columns in the Model" unchecked, but the associations and nav props are still being generated.
thanks in advance

You must edit the t4 template that builds the model classes to get this done.
In your project you'll find two .tt files, something like ModelName.Context.tt and ModelName.tt. The latter is the one that builds the model classes.
Look for these two lines
this.<#=code.Escape(navigationProperty)#> = new HashSet<<#=typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType())#>>();
(probably around line 50)
and
<#=codeStringGenerator.NavigationProperty(navigationProperty)#>
(probably around line 100)
and erase these lines.
Now when you save the template, your classes will be re-generated without navigation properties.

SOLUTION FOUND
As i was reading the conceptual model, i was getting innaccurated information about the table structure, because the conceptual model on the edmx, because when we have foreign keys, associations are created and Nav props instead of regular property (on the fields withing the FK).
The solution i Found is use the store model instead of Conceptual model
Getting the Conceptual Model "Wrong way"
MetadataLoader loader = new MetadataLoader(this);
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
Getting the Store Model "GOOD way"
MetadataLoader loader = new MetadataLoader(this);
StoreItemCollection ItemCollection = null;
loader.TryCreateStoreItemCollection(inputFile, out ItemCollection);

Related

Core Data Relationships are not migrated (Custom Migration)

I really don't know where else to search for a solution to this problem. Basically, I've read twice (or more) all documentation and all pages I found on the web about Core Data Migration.
I had to change some names on the Entities (to readability) and also had to change the domain values used in my entities. AFAIK, in this case, I have to make a custom migration because I have to analyze the Input and generate a new Output:
I've created the new Model Version (v7)
I've updated the Model
Renamed existent Entities, Attributes and Relationships.
Added/Removed some Attributes
I've created the Mapping Model (v6 to v7)
I've configured the Mapping Model using Expressions
I've created two NSEntityMigrationPolicy (one for each entity)
The migration is going well for the entities and fields values, but none of the relationships are getting restored during the process.
During the process, the expression:
FUNCTION($manager, "destinationInstancesForEntityMappingNamed:sourceInstances:" , "RecentCallToRecentRecord", $source.recents)
is returning nothing.
I have debugged my custom NSEntityMigrationPolicy to check if the Source and Destination Entities are bound as expected and something very weird is happing. During the execution of createDestinationInstancesForSourceInstance:entityMapping:manager:error: everything is OK, after calling the superclass, I can navigate from Source to Destination (and the other way around). But during the execution of createRelationshipsForDestinationInstance:entityMapping:manager:error: this objects navigation does not work anymore.
Thanks in advance for any help.

ASP.NET MVC: Adding controller, what to set as model/data context?

I'm using MVC 4 and EF and I'm new to both. I've created an entity named TimesheetModel from an existing DB.
Question: When creating a controller (using the EF framework template) I have several options available to me under both "Model Class" and "Data Context class" dropdowns. By convention, would one usually create a controller per each model you needed to access? And the same for data-context? Also I'm not 100% sure on the data-context portion either.
I've gone through a few tutorials this morning on the topics but they seem to shy away from explaining the "why" you select what you select in those fields. Halp meh! Thx
In the Model Class, you select the class which you want EF to generate its Actions.
In the Data Context class, you type in the "Context" class in which all classes are declared. The context usually is the class which is the main where all starts exactly. If u used code first, you first create Context class, which shows which other classes are creating under it. Otherwise, if u do Database First, then the context is the name of the database usually.
Hope I could explain so you could understand.
The data context represents your database. Usually, in small application, there is only one.
The Model represents an entity, that almost always represents a table in database.
By convention, would one usually create a controller per each model
you needed to access?
It depends on the model. If you have a User class, you usually need to have a UsersController, to create, update and delete an user. If you have a UserRole class, you don't need an UserRoleController because it has a relation with User and you can use UsersController to handle UserRole too.
Keep in mind that there is no rule for that. You can do whatever you want. The Scaffolding of the MVC is just for teaching proposes.

Code First and Model First in the same project?

I have two databases that I am accessing. The first is against a contact database which I connected to using EF Model First; creating the edmx. I have since begun to learn the virtue of CODE First when working with Entity Framework, so I decided I would, in the same project, write the Product database using Code First techniques, allowing the database to be generated from the code I am writing.
Everything compiles fine. The problem occurs when I hit my harness and it attempts to create the Product database and retreive a list of values from one of the tables...
I get the folowing error "Could not find the conceptual model type for 'Core.Data.Account'", when I attempt to enumerate the ProductLines property (Line3 below).
1. using (var ctx = new ProductDb())
2. {
3. var lines = ctx.ProductLines.ToList();
4. this.litOne.Text = lines.Count.ToString();
5. }
After some research it appears that this message may be occuring because of multiple entities with the same name (regardless of namespace), however there is nothing in the ProductDb context with the name "Account".
There is a class in the OTHER context created by the Model First approach named "Account". But how/why would that make a difference? They each point to different databases i.e. different connection strings. Why would the ProductDb be attempting to create a table called Account, when it should be completely unaware of it's exstence?
thoughts?
Thank you as always!,
- G
I bumped into the same problem, but the other way around: first a DbContext + generated database and then generated an edmx off the database (just for a little presentation). It appeared to be a restriction in EF: EF currently has a restriction that POCO classes can't be loaded from an assembly that contains classes with the EF attributes.
The only thing you can do for now is keep the contexts in separate assemblies.

ASP.NET MVC Entity Framework CodeFirst Many To Many (CRUD)

I have a few problems but I'm going to start with the first and smallest. I have two models with a many-many relationship, Category and Project. In each model I have an ICollection of the other model. I initialize the collection as a new HashSet() for the Project constructor and vice-versa for the Category. I've read online that this will create a new table in your database with the PK of each model as the PK in the new table. I custom named them and whatnot through Fluent API but you get the idea.
This worked out great. So I make my Controllers and create and use scaffolding to create the CRUD views. I create a few categories.. Great. Now when I get to creating a a new Project, what I want is it to show me a list of the Categories I previously created, and to require at least one be selected before pushing through the Project. The view shows no categories to select at all and allows it to go through as null. I know how to make a property required but I don't know how to make a collection property required and grab all of the categories from the database to present in the Project create view for selecting....
Try :
Context.Project.Include(p=>p.Category)
inside your query code,
you will need
using System.Data.Entity;
to get the include method
For enabling lazy load, you will also need to mark your properties as "virtual"; otherwise, you will always have to eager load them using the .Include() method.

Are there Visual Studio Tools For Creating DTO/ViewModel

I'm trying to introduce ASP.Net MVC to my department. I am encouraging them to have a ViewModel per View and AutoMapper for our larger projects (and ideally in general).
Sometimes this means having one large entity and picking 5 of its properties and creating the ViewModel. This is done by looking at the the edmx model (many projects were existing so it was DB first) and then creating matching properties in a ViewModel class. Obviously names etc have to match for AutoMapper to work. Also for navigation properties you have to add the navigation name first. Ideally also being able to type in a display name etc.
I'm trying to ease them into doing this (what they see as extra work). Is there any tool that would load a list of fields and allow you to select via checkbox etc and create the class from that?
I guess the same would apply to DTOs etc
Thanks
Have you tried this http://www.codesmithtools.com/product/generator
you can create a template of the dto and then it will generate the files/dto's for you as needed from any kind of datasource.

Resources