Entity framework database first - Table per hierarchy (TPH) recursive relationship implementation - c#

I am trying to implement TPH recursive relationship on one of the concrete types using Entity Framework 5 and Database first approach.
I have conceptual model, and table structure like this:
Also, i have recursive relationship like this in my database table.
ALTER TABLE [dbo].[BaseType]
WITH CHECK ADD CONSTRAINT [FK_BaseType_DerivedType]
FOREIGN KEY([Derived1RecursiveId])
REFERENCES [dbo].[BaseType] ([Id])
When i update model with this relation i get diagram like this:
My question is:
How can i implement a recursive relationship in a database so that when model is updated from database (refreshed), recursive relationship is set on DerivedType1?

It is not possible for the EF model to automatically deduce that the Derived1RecourseiveId is part of the Derived1 class. But you can move the association in your edmx file manually. Just move the foreign key column, delete the association on your base table and recreate it on the derived. Once moved it will stay in your derived type even if you do a model refresh.

Related

EF6 Table Splitting with foreign keys (Database first)

I'm currently investigating the possibility to use table splitting with EF to stop pulling too many columns for nothing. As for now, I'm able to create a new entity, cut/paste the fields into the sub-entity and map it without much problems.
However, if one of those fields is a FK in the master table, it gives me the following error
"Running transformation: There is no property with name 'IdDocumentImportSource' defined in type referred by Role 'DocumentImports'."
I do understand that the both tables have a NavigationProperties that cannot be resolved anymore by the association FK because the field has been moved to the child table.
Here's my question; Is there a way to automaticaly move the association FK to the child table? I could only make it work by manually deleting the association, both navigation properties, creation the association FK of the child. It involves quite a lot of work on my part if I have to do all this manually for every association FK I got...!
DocumentImports is the ParentTable that I splitted into a new child table DocumentImports_StatusDetail and DocumentImportSources is the table being referenced by the FK.
Thanks!

Create a pseudo foreign key on a view using entity framework

I have created a view "Supplier" that shows columns from a table "T_ADDRESS". The view is declared as (I know, the '*' is a no-go in views)
create View Supplier as
select * from T_ADRESSEN where IsSupplier = 1
In EF, I want to use the view as it is more readable than the ugly "T_ADRESSEN". So far so easy.
Now comes the tricky part (for me). The table T_ADDRESS has a self referencing foreign key "MainAddressId" which points to T_ADDRESS.
Creating a DB-first (or CodeFirst from DB) will create the FK relationship for the table T_ADDRESS (and the navigational properties), but not for the view 'Supplier'. Of course not: EF does not know anything about the FK relationship (although the view exposes the same columns).
Now I tried to use the 'ForeignKey' and 'InverseProperty' attributes in my code first model on the Supplier-class but this gives me an ModelValidationException. Also clear: There is no such FK-relationship.
How can I tell EF to treat a field just like a foreign key although the constraint does not exist?
What I am trying to do is to have 'Suppliers' in my EF model (as a subset of T_ADDRESS). If there is another way to do it, I would be happy to receive a hint.
You can't define ForeignKey and InverseProperty on a view. In your case, you need to use that ugly T_ADRESSEN table and use [AutoMapper][1] to map it the to the DTO class. In your case, T_ADRESSEN is the context table and Supplier is your DTO class.
with AutoMapper you can do something like this:
var ugly = context.T_ADRESSEN.Where(e=>e.IsSupplier ==1);
var suppliers = mapper.Map<IEnumerable<Supplier>>(ugly);
where mapper is IMapper interface defined in AutoMapper.
Sometime one should figure out that the DTO mapping technique as a replacement to the traditional database view.

Modelling polymorphic associations database-first vs code-first

We have a database in which one table contains records that can be child to several other tables. It has a "soft" foreign key consisting of the owner's Id and a table name. This (anti) pattern is know as "polymorphic associations". We know it's not the best database design ever and we will change it in due time, but not in the near future. Let me show a simplified example:
Both Event, Person, and Product have records in Comment. As you see, there are no hard FK constraints.
In Entity Framework it is possible to support this model by sublassing Comment into EventComment etc. and let Event have an EventComments collection, etc.:
The subclasses and the associations are added manually after generating the basic model from the database. OwnerCode is the discriminator in this TPH model. Please note that Event, Person, and Product are completely different entities. It does not make sense to have a common base class for them.
This is database-first. Our real-life model works like this, no problem.
OK. Now we want to move to code-first. So I started out reverse-engineering the database into a code first model (EF Power Tools) and went on creating the subclasses and mapping the associations and inheritance. Tried to connect to the model in Linqpad. That's when the trouble started.
When trying to execute a query with this model it throws an InvalidOperationExeception
The foreign key component 'OwnerId' is not a declared property on type 'EventComment'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.
This happens when I have bidirectional associations and OwnerId is mapped as a property in Comment. The mapping in my EventMap class (EntityTypeConfiguration<Event>) looks like this:
this.HasMany(x => x.Comments).WithRequired(c => c.Event)
.HasForeignKey(c => c.OwnerId);
So I tried to map the association without OwnerId in the model:
this.HasMany(x => x.Comments).WithRequired().Map(m => m.MapKey("OwnerId"));
This throws a MetaDataException
Schema specified is not valid. Errors:
(10,6) : error 0019: Each property name in a type must be unique. Property name 'OwnerId' was already defined.
(11,6) : error 0019: Each property name in a type must be unique. Property name 'OwnerId' was already defined.
If I remove two of the three entity-comment associations it is OK, but of course that's not a cure.
Some further details:
It is possible to create a working DbContext model ("code second") from the edmx by adding a DbContext generator item. (this would be a work-around for the time being).
When I export the working code-first model (with one association) to edmx (EdmxWriter) the association appears to be in the storage model, whereas in the original edmx they are part of the conceptual model.
So, how can I create this model code-first? I think the key is how to instruct code-first to map the associations in the conceptual model, not the storage model.
I personally stick with Database first when using EF on any schema that is this level of complexity. I have had issues with complex schemas in regards to code first. Maybe the newer versions are a little better, but worrying how to try and code complex relationships seems less straight forward then allowing the engine to generate it for you. Also when a relationship gets this complex I tend to avoid trying to generate it with EF and try and use stored procedures for easier troubleshooting of performance bottlenecks that can arise.

Entity Framework 4 and SQL Server 2008 Multiple Possible Foreign Keys

I am trying to come up with a database design that would work with Entity Framework 4 Code First. Actually, I have no experience yet of EF4 Code First but as I understand it, if I write the code, it will create the database and tables.
The issue is this. There are various types of auctions, they all have some common fields and some specific ones. In the code I envisage having a base abstract class called Auction and subclasses like LowestUniqueBidAuction and EnglishForwardAuction etc.
Nothing surprising there. The problem is that I imagine the database structure to mimic this. I imagine an Auction table and a LowestUniqueBidAuction table and a EnglishForwardAuction table. In the Auction table I imagine a foreign key into one of these two tables for each row depending on the type of auction that that row is. I also imagine another column in the Auction table with the name of the derived auction table (such as EnglishForwardAuction).
The problem is that whenever I've ever created a foreign key I've had to specify the name of the foreign table into which the key points (which makes sense). In this case, however, there is one of many tables that the key could point. So there are many issues here. Firstly, I could simply not use a foreign key and just use an ordinary field, but then the database will not be able to maintain data consistency for me. The second issue is how will EF Code First handle this? In other words, how will it know that if I ask for all EnglishForwardAuction rows from the Auction table that it should look at the column with the table name and then join on the EnglishForwardAuction table to get the extra fields?
Has anyone ever faced similar issues?
Thanks,
Sachin
This problem is solvable in Entity Framework in a number of ways - read up on how EF handles inheritance and what strategies are available.
There are basically three strategies how to handle this:
(1) Table per Hierarchy
You have only one single table, that represents all possible sub classes. Of course, this means, several rows (that only exist in a given subclass) must be nullable, since they don't show up / don't exist in super classes or other subclasses.
(2) Table per Type
Each subclass gets its own table, and by default, the sub-types table shares the PK with the base classes' table - e.g. PK = 1 in Auction will also be PK = 1 in EnglishForwardAuction. So your subclass tables reference the base table - not the other way around.
(3) Table per Concrete Type
Each concrete subclass (your separate auction types) gets its own table, but that table contains everything - all the columns, from that specific type, but also its base type.
Read more here:
Inheritance in the Entity Framework
Inheritance and Associations with Entity Framework Part 1
Entity Framework Modeling: Table Per Hierarchy Inheritance
Entity Framework Modeling: Table Per Type Inheritance
Searching for Entity Framework Inheritance and/or one of these strategies will reveal a lot more hits, too - that topic is very well covered and discussed on the interwebs! :-)

Problems with automatic property creation when manually mapping relationships between tables with no foreign keys in L2S

Pardon the massive headline.
I'm in the situation of having to build an application on top of a database, that I cannot make any changes to. The database does not have any primary- or foreignkeys set.
I'm using linq-2-sql, and I'm interested in having some properties exposed on the entities generated from my dbml. For instance, in the hypothetical example of a one-to-many relationship between table education and student - where each student record has a reference to an education id, I'd like to be able to go:
var student = GetAStudentFromContextOrWhatever();
var studentsEducation = student.Education;
It is my experience, that this kind of property is automatically generated when I drag'n'drop tables with foreignkey relationships from the server explorer.
However as previously mentioned, in this case I do not have these foreign key relationships - rather I am adding the relationships manually in the dbml file, specifying parent and child class.
When I add these relationships, I expect the involved entities in the designer.cs of my context to get populated with properties of a kind like those described above.
This, however, does not happen.
What must I do for my dbml to create these properties for me - based on these manually mapped associations between entities/tables that, on a database level, do not have foreign key associations?
Cheers!
L2S is just that Linq-to-SQL. If it isn't in SQL it won't be generated. The expression trees behind L2S just can't understand what you are doing. The place for your association is in a partial class file which you will have create manually. Also it probably won't update or insert through the association.
I know this is a very old question, but I just ran into the same problem. In order for the relationship in the DBML designer to automatically create the association properties for you, you need to have primary keys on your objects. If you click the column name in the designer, you'll see that your PK field has PrimaryKey = false. Switch that to True and build; all should be well.
Patrick

Categories

Resources