Entity Framework Conditional Mapping - entity-framework

I have a legacy database that has a table called Address. Now two other tables can have address information assigned to it. To determine which table it came from, there is a SourceID field. If the SourceID is 1 then it is associated with the first table, if it is 2, it is address information for the second table.
This legacy database doesn't have any foreign key constraints defined on the database, and it cannot be added.
I am wondering if I use Entity Framework to create a model that will have this association. Where table 1 can have an entity that has a navigation to address information (with the condition that the SourceID =1) and same with the second table.
I have tried created a conditional mapping and have it set "When SourceID = 1" I also removed the mapping from the column mapping as the column can only be mapped once. When I try to compile, I get the following error:
Error 3004: Problem in mapping fragments starting at line 683: No mapping specified for properties Address.SourceID in Set Addresses. An Entity with Key (PK) will not round-trip when: Entity is type [Model.Address]
Thanks for your help!

Don't use conditional mapping. Map your address to the entity without SourceID property and create two derived entities from the address entity. Use SourceID as discriminator (TPH inheritance - it works same as conditional mapping but you have multiple entities with different discriminator value). Relate your first and second entity to correct address sub entity.

Related

How to create relationships between entities with existing database that does not contain foreign keys

Using Entity Framework Core 2.0
Stuck with company's production database which has primary keys defined for each table but no foreign keys defined for any relationships.
Dependent records in the database have id fields which are intended to relate to the primary key fields of the parent record like you would normally find with a foreign key relationship/constraint. But these fields were all created as INT NOT NULL and are using a SQL default of '0'.
As a result dependent records have been inserted over time without requiring that a related parent record be specified.
Initially I defined my models in EF with integers and used a fluent configuration to specify "IsRequired". This was done so I could run migrations to create a test database for comparison against the production database to verify that my code first was correctly coded.
This then lead to the problem while using "Include" in my Linq queries which performs an inner join that results in dropping the records that contain the 0's in the id fields of the dependent record.
The only way that I have found to make this work is to model all of the id fields in the dependent entity as nullable integers and remove the "IsRequired" from the fluent configuration.
When using the "Include" it performs a left outer join keeping all of the dependent entities. This also means that any reference properties on the included entities are set to null instead of an empty string. This part can probably be fixed fairly easily.
The downside is if I wanted to use migrations to create a database now, all id fields in the dependent records would be created as NULL.
Is there anyone who has run up against this type of situation? Does anyone have any suggestions to try other than the approach I am using?
I haven't dealt with this scenario before but I wonder if you can solve it by defining the FK property as Nullable and then in the migrations, after the migration is created, edit it to add a HasDefaultValue property to ensure that it's 0? (doc for that migration method: https://learn.microsoft.com/en-us/ef/core/modeling/relational/default-values)

Select Specific Columns from Database using EF Code First

We have a customer very large table with over 500 columns (i know someone does that!)
Many of these columns are in fact foreign keys to other tables.
We also have the requirement to eager load some of the related tables.
Is there any way in Linq to SQL or Dynamic Linq to specify what columns to be retrieved from the database?
I am looking for a linq statement that actually HAS this effect on the generated SQL Statement:
SELECT Id, Name FROM Book
When we run the reguar query generated by EF, SQL Server throws an error that you have reached the maximum number of columns that can be selected within a query!!!
Any help is much appreciated!
Yes exactly this is the case, the table has 500 columns and is self referencing our tool automatically eager loads the first level relations and this hits the SQL limit on number of columns that can be queried.
I was hoping that I can set to only load limited columns of the related Entities such as Id and Name (which is used in the UI to view the record to user)
I guess the other option is to control what FK columns should be eager loaded. However this still remains problem for tables that has a binary or ntext column which you may not want to load all the times.
Is there a way to hook multiple models (Entities) to the same table in Code First? We tried doing this I think the effort failed miserably.
Yes you can return only subset of columns by using projection:
var result = from x in context.LargeTable
select new { x.Id, x.Name };
The problem: projection and eager loading doesn't work together. Once you start using projections or custom joins you are changing shape of the query and you cannot use Include (EF will ignore it). The only way in such scenario is to manually include relations in the projected result set:
var result = from x in context.LargeTable
select new {
Id = x.Id,
Name = x.Name,
// You can filter or project relations as well
RelatedEnitites = x.SomeRelation.Where(...)
};
You can also project to specific type BUT that specific type must not be mapped (so you cannot for example project to LargeTable entity from my sample). Projection to the mapped entity can be done only on materialized data in Linq-to-objects.
Edit:
There is probably some misunderstanding how EF works. EF works on top of entities - entity is what you have mapped. If you map 500 columns to the entity, EF simply use that entity as you defined it. It means that querying loads entity and persisting saves entity.
Why it works this way? Entity is considered as atomic data structure and its data can be loaded and tracked only once - that is a key feature for ability to correctly persist changes back to the database. It doesn't mean that you should not load only subset of columns if you need it but you should understand that loading subset of columns doesn't define your original entity - it is considered as arbitrary view on data in your entity. This view is not tracked and cannot be persisted back to database without some additional effort (simply because EF doesn't hold any information about the origin of the projection).
EF also place some additional constraints on the ability to map the entity
Each table can be normally mapped only once. Why? Again because mapping table multiple times to different entities can break ability to correctly persist those entities - for example if any non-key column is mapped twice and you load instance of both entities mapped to the same record, which of mapped values will you use during saving changes?
There are two exceptions which allow you mapping table multiple times
Table per hierarchy inheritance - this is a mapping where table can contains records from multiple entity types defined in inheritance hierarchy. Columns mapped to the base entity in the hierarchy must be shared by all entities. Every derived entity type can have its own columns mapped to its specific properties (other entity types have these columns always empty). It is not possible to share column for derived properties among multiple entities. There must also be one additional column called discriminator telling EF which entity type is stored in the record - this columns cannot be mapped as property because it is already mapped as type discriminator.
Table splitting - this is direct solution for the single table mapping limitation. It allows you to split table into multiple entities with some constraints:
There must be one-to-one relation between entities. You have one central entity used to load the core data and all other entities are accessible through navigation properties from this entity. Eager loading, lazy loading and explicit loading works normally.
The relation is real 1-1 so both parts or relation must always exists.
Entities must not share any property except the key - this constraint will solve the initial problem because each modifiable property is mapped only once
Every entity from the split table must have a mapped key property
Insertion requires whole object graph to be populated because other entities can contain mapped required columns
Linq-to-Sql also contains ability to mark a column as lazy loaded but this feature is currently not available in EF - you can vote for that feature.
It leads to your options for optimization
Use projections to get read-only "view" for entity
You can do that in Linq query as I showed in the previous part of this answer
You can create database view and map it as a new "entity"
In EDMX you can also use Defining query or Query view to encapsulate either SQL or ESQL projection in your mapping
Use table splitting
EDMX allows you splitting table to many entities without any problem
Code first allows you splitting table as well but there are some problems when you split table to more than two entities (I think it requires each entity type to have navigation property to all other entity types from split table - that makes it really hard to use).
Create stored procedures that query the number of columns needed and then call the stored procs from code.

Entity Framework 4.1 Code First: How is the Discriminator determined?

Currently I have class hierarchy defined with the Code First approach as follows.
E.F. has autogenerated a nvarchar(128) discriminator. It is not a key field.
How does Entity Framework determine what and what Type the discriminator field should be, and is it always the same, i.e. nvarchar? Is the discriminator at all accessible outside the database i.e. from LINQ to Entity?
Discriminator column is by default nvarchar because it stores names of your classes to differ between types - that is the whole point of this column: to allow EF knowing what class instance from your inheritance hierarchy it should create when it loads record from the database.
Discriminator column is not accessible by linq-to-entities. It is only used to map record to correct type.

Linq Mapping Problem with 1 to 0.1 relationships

I have an linq to entity mapping issue. I have three tables.
Table 1 - ItemsB(ID(key), Part_Number(will be null until built), other item b information)
Table 2 - ItemsA(ID(key), Part_Number(will be null until built), other item a information)
Table 3 - WebItems(Item_id, web item information) *Consists of items from both ItemsB and ItemsA after they are built and pushed over to this table.
ItemsA/ItemsB will have a 1 to 0.1 relationship with WebItems. Part_Number maps to Item_id.
I am using EF4.0.
Problem is after i set up the association/mappings as stated above i get an error message stating: "Problem in mapping fragment at lines so and so: Column [Part_Number] are being mapped in both fragments to different conceptual side properties."
Usually i know what to do in this case. Get rid of the property [Part_Number]. Problem is i need to access [Part_Number] in both ItemsB and ItemsA quite frequently without going to webitems. Not to mention webitems will not always have the [Part_Number] populated at certain points depending upon whether the items have be pushed to webitems.
Does anyone know how to get around this?
Thanks in advance.
As I understand it ItemA and ItemB to WebItem in one-to-one relation. One-to-one relation in EF always demands that relation is build on primary keys and one side is mandatory (principal) because dependent entity will have primary key and foreign key in one column. Once you assign primary key in dependent entity you must have principal entity with the same primary key otherwise you will violate referential integrity defined by foreign key.
The problem is that your Part_Number is primary key and foreign key in the same time. To allow such mapping in EFv4 you must use Foreign Key association instead of Independent association. Here is brief description how to create foreign key association in the designer. Once you define referential constrain get back to mapping window of association and delete the mapping.

Entity Framework - Association From Derived Entities

I'm using the TPH (Table per Hierarchy) technique to map a set of entities.
DB Schema:
UserGroupLabelSpreads table having a "UserId", "GroupId" and "LabelId" nullable fields with some additional common fields.
DAL Objects:
- UserGroupLabelSpread abstract class.
- UserSpread with a discriminator having only non-null UserId.
- GroupSpread with a discriminator having only non-null GroupId.
- LabelSpread with a discriminator having only non-null LabelId.
I've managed to get this thing to work, but when I try to connect the UserSpread entity to an existing "User" entity, I'm getting the following error:
Error 1 Error 3034: Problem in Mapping Fragments starting at lines 487, 554: Two entities with different keys are mapped to the same row. Ensure these two mapping fragments do not map two groups of entities with overlapping keys to the same group of rows.
I've digged around to understand that the problem is that I'm mapping the UserId column twice: once for the discriminator condition and second for the association.
Am I right with my assumption? -Can I get this thing to work?
Thanks,
Nir.
There is an updated version of EDM Generator which should be able to help you. You can use it to generate, validate and more. Sorry, got the wrong link. Here is the one to v2. I believe I've had this issue. If I am not mistaken it was due to me mapping the forreign keys wrong. I was however using beta 1 of EF4 at that time and some of the messages was wrong due to the proxies. Check your forreign keys. Blog.Id ---> Blog_id was my issue. I had Blog.Id --> Blog.Id and then BlogEntry.Id ----> Blog.Blog_Id which of course doesn't work but the designer is kind of unforgiving when it comes to mapping keys.