Entity Framework 'Update Model from Database' recreating associations between base and sub classes - entity-framework

I am trying to implement a number of base/sub classes using Entity Framework, database first. Following some online tutorials, I have decided to attempt TPT inheritance.
On the database, I have a base class table 'Location', and two sub class tables: 'StreetAddress' and 'RuralRouteAddress'. I have defined a foreign key constraint between the sub class tables and the base class table on their primary keys. 'Location's Primary Key is an auto-increment column, and the two sub class tables' primary keys are not auto-increment.
In Entity Framework, I defined the 'Base Type' of the two sub classes as 'Location'. I then deleted the associations (and their corresponding navigation properties) from the model. I also deleted the ID column mappings from the sub classes, as ID is now inherited from the 'Location' base class.
This seems to have worked. I haven't tried updating/inserting, but querying returns the data with proper inheritance in place.
My problem is that, whenever I 'Update Model from Database', he inheritance association lines stay, but the FK associations between the base class and the sub classes are brought back... . I then have to delete them, and realign the association lines on my diagram (I'm a bit picky about the layout of the model diagram).
This isn't so bad, but the project that I would like to use TPT inheritance in has a lot of inheritance. Having to delete a ton of associations and reorganize my entire diagram every time I update the model is not very appealing.
Did I do something wrong when I implemented inheritance? Is there a way to ignore/exclude certain associations from being created when updating the model?

The relationships you define in the database will always reappear when you update the model from the database. This is by design. If you want to have classes in the model that have a different relationship structure, try creating a complex model from a stored procedure that selects all the columns (or all the columns you want) from the base table. Import that procedure and in the Function Imports, edit the return type by creating a new complex type, or even just renaming the result that EF automatically creates. Then add your associations on that type, and use it as the base type for your inherited classes.
The good part of this is that you can adjust the type structure to match any table changes by editing the stored procedure, then using "Get Column Information" and "Update" to bring the complex type into line. It won't overwrite your associations because they aren't defined in the database, but it is almost as straightforward as using TPT.
Joey

Related

Entity Framework: Doing JOINs without having to creating Entities

Just starting out with Entity Framework (Code First) and I have to say I am having a lot of problems with it when loading SQL data that is fairly complex. For example, let's say I have the following tables which stores which animals belongs to which regions in the world and the animal are also categorized.
Table: Region
Id: integer
Name string
Table AnimalCategory
Id integer
Name: string
RegionId: integer -- Refers back Region
Table Animal
Id integer
AnimalCategoryId integer -- Refers back AnimalCategory
Let's say I want to create a query with Entity Framework that would load all Animals for a specific region. The easiest thing to do is to create 3 Entities Region, AnimalCategory, and Animal and use LINQ to load the data.
But let's say I am not interested in loading any AnimalCategory information and define an Entity class just to represent AnimalCategory so that I can do the JOIN. How can I do this with Entity Framework? Even with many of its Mapping functions I still don't think this is possible.
In non Entity Framework solutions this is easy to accomplish by using INNER JOINs in SPs or inline SQL. So what are my options in Entity Framework? Shall I pollute my data model with these useless tables just so I can do a JOIN?
It's a matter of choice I guess. EF choose to support many-to-many associations with transparent junction tables, i.e. where junction tables only have two foreign keys to the associated entities. They simply didn't choose to support this far less common "skipping one-to-many-to-many" scenario in a similar manner.
And I can imagine why.
To start with, in a many-to-many association, the junction table is nothing but that: a junction, an association. However, in a chain of one-to-many (or many-to-one) associations it would be exceptional for any of the involved tables to be just an association. In your example...
Animal → AnimalCategory → Region
...AnimalCategory would only have a primary key (Id) and a foreign key (RegionId). That would be useless though: Animal might just as well have a RegionId itself. There's no reason to support a data model that doesn't make sense.
What you're after though, is a model in which the table in the middle does carry information (AnimalCategory.Name), but where you'd like to map it as a transparent junction table, because a particular class model doesn't need this information.
Your focus seems to be on reading data. But EF has to support all CRUD actions. The problem here would be: how to deal with inserts? Suppose Name is a required field. There would be no way to supply its value.
Another problem would be that a statement like...
region.Animals.Add(animal);
...could mean two things:
add an Animal and a new AnimalCategory, the latter referring to the Region.
Add an Animal referring to an existing AnimalCategory - without being able to choose which one.
EF wouldn't want to choose for some default behavior. You'd have to make the choice yourself, so you can't do without access to AnimalCategory.

Entity Framework Model First and Code First TPH issue

I'm facing two problems by trying to make a model first or code first using TPH concept.
The problem is that I need to use table per hierarchy at three levels, so that:
When I use Model First, the last hierarchy entity (third level) does not saves in database. I create an instance from this entity which inherits an abstract entity, which inherits another abstract entity. The data of two abstract entities are saved, but the last entity not saves. If the inheritance goes at maximum two levels works fine.
If I try to use Code First the problem is that I cannot share attributes with same name, for example: ClassB and ClassC has a property named "Name", and both inherits ClassA. When I map to generate database, I want to create only a sql table called ClassA, but it does not share the column "Name", it creates Name and Name1 columns.
I need to do one of this models works, otherwise I can't use inheritances in my model.
Hope some help!
Thanks

Entity Framework 4.1 Complex Type reuse in different models

Here is the senario for which I could not find anything useful. Maybe Im the first person thinking of doing it this way:
Approach: Database First
Database: SQL Server 2008 R2
Project : DLL (Data Access)
I have a data access library which encapsulates all the access to database as well as the biz functionality. The database has many tables and all the tables have the following 2 columns:
last_updated_on: smalldatetime
last_updated_by: nvarchar(50)
The project contains several models (or edmx files) which contain only related entities which are mapped to the tables they represent. Since each of the table contain the columns for last_updated_* I created a complex type in one of the models that is as follows:
Complex Type: History
By (string: last_updated_by)
On (DateTime: last_updated_on)
The problem is that it can only be used in the model in which I defined it.
A) If I try to use it in other model it does not show it in the designer
B) If i define it in the other models I get error History already defined
Is there any solution so that the History complex type, defined in one model can be reused by other models?
I was trying to do almost the exact same thing (my DB fields are "created", "creatorId", "modified", and "modifierId", wrapped up into a complex type RecordHistory) and ran into this question before finding an answer...
http://msdn.microsoft.com/en-us/data/jj680147#Mapping outlines the solution, but since it's fairly simple I'll cover the basics here too:
First create the complex type as you did (select the fields in the .edmx Designer, right click, select "Refactor into New Complex Type")
In the .edmx Designer (NOT the Model Browser) right click on another table/entity that has the same common columns and select Add -> Complex Property
The new property will be assigned a complex type automatically. If you have more than 1 complex type, edit the new property's properties and set the Type appropriately
Right-click on the table/entity again (in either the Model Browser or Designer) and select Table Mapping
Update the Value/Property column for each of your common fields (changing them, in my case, from "modified : DateTime" to "history.modified : DateTime")
Delete the old common fields from your entity, leaving just the complex type in their place

Entity Framework Table Per Hierarchy restrictions

I have very big table in my Database and a can't modify it.
So i have BaseEntity type for table.
I have several children (entity1, entity2) and i'd like to map each type to same column ("Date") and name properties differently.
Surely i can't move all same column properties to base type cause there is about 100 columns in my super table (it's not my design i've jst need to map it)
So i have 0019 error and is there any way to solve it or EF not for me?
No. TPH requires that each property defined in derived entity is exclusive for that entity (no other entity can map to the same column). This targets more general rule in EF - each column can be mapped only once. So if you need to use some column in more entities it must be defined in parent and must have same name in all child entities.

EF Table-per-hierarchy mapping

In trying to normalize a database schema and mapping it in Entity Framework, I've found that there might end up being a bunch of lookup tables. They would end up only containing key and value pairs. I'd like to consolidate them into one table that basically has two columns "Key" and "Value". For example, I'd like to be able to get Addresses.AddressType and Person.Gender to both point to the same table, but ensure that the navigation properties only return the rows applicable to the appropriate entity.
EDIT: Oops. I just realized that I left this paragraph out:
It seems like a TPH type of problem, but all of the reading I've done indicates that you start with fields in the parent entity and migrate fields over to the inherited children. I don't have any fields to move here because there would generally only be two.
There are a lot of domain-specific key-value pairs need to be represented. Some of them will change from time to time, others will not. Rather than pick and choose I want to just make everything editable. Due to the number of these kinds of properties that are going to be used, I'd rather not have to maintain a list enums that require a recompile, or end up with lots of lookup tables. So, I thought that this might be a solution.
Is there a way to represent this kind of structure in EF4? Or, am I barking up the wrong tree?
EDIT: I guess another option would be to build the table structure I want at the database level and then write views on top of that and surface those as EF entities. It just means any maintenance needs to be done at multiple levels. Does that sound more, or less desireable than a pure EF solution?
Table per hiearchy demands that you have one parent entity which is used as base class for child entities. All entities are mapped to the same table and there is special discriminator column to differ type of entity stored in database record. You can generally use it even if your child entities do not define any new properties. You will also have to define primary key for your table otherwise it will be handled as readonly entity in EF. So your table can look like:
CREATE TABLE KeyValuePairs
(
Id INT NOT NULL IDENTITY(1,1),
Key VARCHAR(50) NOT NULL,
Value NVARCHAR(255) NOT NULL,
Discriminator VARCHAR(10) NOT NULL,
Timestamp Timestamp NOT NULL
)
You will define your top level KeyValuePair entity with properties Id, Key, Value and Timestamp (set as concurrency mode fixed). Discriminator column will be used for inheritance mapping.
Be aware that EF mapping is static. If you define AddressType and Gender entities you will be able to use them but you will not be able to dynamically define new type like PhoneType. This will always require modifying your EF model, recompiling and redeploying your application.
From OOP perspective it would be nicer to not model this as object hiearchy and instead use conditional mapping of multiple unrelated entities to the same table. Unfortunatelly even EF supports conditional mapping I have never been able to map two entities to the same table yet.