Modelling polymorphic associations database-first vs code-first - c#

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.

Related

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.

Code first of EF, how to define navigation property relationship without setting foreign key between table in database

I use code first of Entity framework. There are two classes "Question" and "User". I defined a relationship as below:
this.HasRequired(v => v.Creator).WithMany(v => v.Questiones)
.HasForeignKey(v => v.CreatorId).WillCascadeOnDelete(false);
After gernerating the database I found that it always create foreign key between Id of User and CreatorId of Question. Because of lower performance of FK(and other reason),I want to define navigation property relationship without setting foreign key in database? Delete FK after EF created it?
If cannot do this using fluent api, could you tell me why EF designed in this way please?
About the lower performance of FK. I have a User table with 5 Million records in it. when I insert a Question into db, since the db check the question.CreatorId validation from User table, it always slower than without FK.
And there are many other reasons that I need to remove FK.
I think I am somewhat obsession because I think that deleting FK after created it is strangely and ugly. What i want is implementing this by using something like WithoutForeignKey in fluent api:
this.HasRequired(v => v.Creator).WithMany(v => v.Questiones)
.WithoutForeignKey(v => v.CreatorId).WillCascadeOnDelete(false);
Without questioning why are you trying to do this strange thing and going just to the answer: you could delete fk constraint after generated, or you could use migrations and remove FK generation from the migration code.
SQL code generated when traversing nav properties will work even if fk constraint doesn't exist, except for cascade deleting
If you want a relationship between two tables, you need to define a foreign key. No way around it. Even if you use Map() in fluent api, you can only hide the foreign key in your model, in the background EF will still use it and it will exist in the database.
Also I don't get what you mean by "performance" of foreign key? One extra (likely small) column won't make a difference. If you mean the navigation properties for the performance part, you can do 3 things:
Don't include them in your model
Make them non-virtual to disable lazy loading
Disable lazy loading all together with ctx.Configuration.LazyLoadingEnabled = false;
If you don't want to tell db about relation and treat both entities as not related (I wonder why), then just ignore these navigation properties and FK field. Note that you will be responsible for managing related entities: saving and loading them from db, updating ids etc
this.Ignore(q => q.Creator);
this.Ignore(q => q.CreatorId);
And you also need to ignore other side of relation, otherwise EF will generate FK column with default name Creator_CreatorId. So in Creator entity configuration:
this.Ignore(c => c.Questiones);

EF DB-first mapping mess

I have a frustrating situation owing to this little quirk of EF. Here's a simple demo of the behavior. First the DB schema:
As you see, RestrictedProduct is a special case of product, which I'm intending to make a subclass of Product with some special code.
Now I import to an EF data model:
Oops! EF saw that RestrictedProduct had only 2 fields, both FKs, so it mapped it as a one-to-many relationship between Product and Restriction. So I go back to the database and add a Dummy field to RestrictedProduct, and now my EF model looks much better:
But that Dummy field is silly and pointless. Maybe I could delete it? I blow away the field from the DB table and the entity model, then refresh the model from the DB...
Oh, no! The Product-Restriction association is back, under a new name (RestrictedProduct1)! Plus, it won't compile:
Error 3034: Problem in mapping fragments starting at lines (x, y) :Two entities with possibly different keys are mapped to the same row. Ensure these two mapping fragments map both ends of the AssociationSet to the corresponding columns.
Is there any way to prevent this behavior, short of keeping the Dummy field on the RestrictedProduct table?
I just came across the same issue, and as an alternative to putting the dummy field in your RestrictedProduct table to force the creation of an entity you can also make your RestrictedProduct.RestrictionId field nullable and EF will then generate an entity for it. You can then modify it to use inheritance and any subsequent "Update model from database" will not cause undesired nav properties. Not really a nice solution but a work around.
Let's walk slowly into your problem.
1st thing you need to decide is if the restricted product is
really a special case of product or is it a possible extension
to each product.
From your original DB Scheme it seems that any product may have
a relation to a single restriction however a single restriction
can be shared among many products.. so this is a simple 1 to many
situation which means that restricted product is NOT a special case
of product! Restriction is an independent entity which has nothing
to do with product in a specific way.
Therefore EF is correct in the 1st importation of your scheme:
1. a product can have 0 or 1 restrictions.
2. a restriction is another entity which can be related to many products.
I do not see your problem.

Polymorphic cross-associations on Entity Framework

OK, this is an interesting and most importably real urgent problem for me to solve... In order for others to neatly comprehend it, I've stretched myself to make a well illustrated post.
The Object Model
So I have this simple, easy and "beautiful" model in mind. See the first picture. (You can ignore PathEntry, it's not relevant in my situation.)
The idea is that a MediaFeedItem owns:
a collection of ThumbnailFileEntries (accesible through the ThumbnailFiles property)
at most 1 raw FileEntry (MetadataFile property) and
at most 1 MediaFileEntry (MediaFile property)
We shall refer to these last three entity types as the file entities.
Now there's more: As you can see, I am inheriting both ThumbnailFileEntry and MediaFileEntry from FileEntry, and let's not debate that! (for now), it's one of those end-of-story aspects of the design and both entity types will continue to grow later on.
This already brings me some significant issues right away in regards to the polymorphic associations induced by the relationships from the file entities to MediaFeedItem.
The first thing that you shall observe is that I have eliminated the navigation property from the derived file entities (ThumbnailFileEntry and MediaFileEntry) to the primary entity MediaFeedItem.
I do this because they already inherit that property defined in the base class FileEntry. As you can see, I do not delete the roles at the end of these associations.
The Relational Model
I shall be using the so-vastly-conceptually-superior TPT strategy for generating and mapping my Object Model to the RDB world (vs TPH/TPC).
I'm using EF5-rc, the EDMX model designer to design my model, and the EF5 DbContext Generator to generate a DbContext and POCOs cuz I wanna use the DbContext API.
As you can see, I can nicely generate the database model using the EF tools:
The Problem
When loading a new MediaFeedItem and saving it, I get the following error:
System.InvalidOperationException: Multicplicity constraint violated. The role 'MetadataFile' of the relationship 'MediaFeedModel.MediaFeedItem_MetadataFile' has multiplicity 1 or 0..1.
What am I doing wrong?
Looking at your problem one thing stands out, The FK relationship between File and MediaFeedItem is required (IE a file must have a MediaFeedItem), but in the case where you are in an extended version of File you probably dont want this.
What i think you want to do is one of the following:
change the multiplicity on MediaFeedItem_FileEntry to 0..1 - 0..1 so that it isnt required at either end
create a new extended type to handle your metadataFile type and remove the direct reference between the base type and MediaFeedItem
I personally think the second is a more elegant solution to your problem as its creating an actual type for your MetadataFile
What appears to be happening is that you are trying to create an extended type but the base type isnt actually a metadata file.

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