Entity Framework Code First - Two tables, same concept, but different types - entity-framework

I have a database with two tables, one with a column numeric (19,4) and other with float.
I need to map (in Entity Framework 5 Code First) this two tables in entities that have the same type, such as decimal. Change the database is the best solution, although is out of question.
Anyone?

Entity Framework does not support such simple mappings (yet?) that require type conversions. It is on a feature request list but apparently not decided until now if simple type mappings will get better support in the future:
http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/2639292-support-for-simple-type-mapping-or-mapped-type-con
A workaround is to use two properties in your model, one that is not mapped to a database column and one with a type matching the actual type in the database, and then to perform the type conversion between the two properties in their getters and setters. An example for this is here:
https://stackoverflow.com/a/14221906/270591

Related

EF Core HasData Seeding a TPH Entity

I want to use the EF Core HasData method to seed a database with reference data. Two of the models I want to seed follow the Table per Hierarchy (TPH) pattern in the sense that there is a none abstract base type and another none abstract derived type. These models in the database exist in a table named after the base type with a discriminator column. I would like to add data seeding for this table. However I’m struggling to find any guidelines of how to do so in the EF Core 6 documentation.
I have a few related questions:
Do I seed all the data using the HasData method on an EntityTypeBuilder<BaseType> or do I need to split the seeding into one HasData on that class and another on EntityTypeBuilder<DerivedType>?
I understand using TPH will add a shadow discriminator property and that, potentially, I’ll have to add that in the data seeding. Does that mean I have to use anonymous types to specify that property (doesn’t seem very elegant) and if so, can I get the autogenerated discriminator name using a method (typing it manually sounds like a risk as what if EF Core changes the discriminator name convention?)?
Should I be avoiding using TPH on reference tables altogether? Is there something else I should do instead?
After going through my options with trial and error, I have come to the following solution. It may not be perfect, but it deals with all of my concerns.
Do I seed all the data using the HasData method on an EntityTypeBuilder<BaseType> or do I need to split the seeding into one HasData on that class and another on EntityTypeBuilder<DerivedType>?
You have to do it on both classes, attempting otherwise throws on creating the migration:
The seed entity for entity type 'BaseType' cannot be added because the value provided is of a derived type 'DerivedType'. Add the derived seed entities to the corresponding entity type.
I understand using TPH will add a shadow discriminator property and that, potentially, I’ll have to add that in the data seeding. Does that mean I have to use anonymous types to specify that property (doesn’t seem very elegant) and if so, can I get the autogenerated discriminator name using a method (typing it manually sounds like a risk as what if EF Core changes the discriminator name convention?)?
I have added a property to the BaseType class and defined it as the discriminator, so now I can specify the discriminator values directly without using anonymous type and I am in control of the discriminator values. Gert Arnold points out in this other answer why this might not be appropriate. However I have used the following method described in this EF Core Github issue to hopefully mitigate the concerns he raised.
Should I be avoiding using TPH on reference tables altogether? Is there something else I should do instead?
This is still unanswered. But I am feeling a lot more confident it is a good approach now.

FSharp Record Types With Entity Framework Code-First

I am doing a proof of concept in a line of business application where I want to swap out the current C# Code-First Entity Framework implementation with a F# one. I am following this article which seems to work pretty well, but I was hoping to use FSharp record types instead of the classes that the article uses. When I try and add a data annotation to a record type like this:
type Family = {[<Key>]Id:int; LastName:string; IsRegistered:bool}
I get the following error:
Error 1 The type 'Key' is not defined
Is there a way to use data annotations with record types? Apparently, EF Code-First needs annotations...
Record types support attributes just fine (and with the syntax you have).
Check if your reference to System.ComponentModel.DataAnnotations is in order, that's where KeyAttribute is defined.
Edit: EF wants to work with properties, that's why using a record doesn't mesh well with EF. You can still make it work in F# 3.0+ by marking the record with CLIMutable attribute (this generates property setters and a parameterless constructor which are taken for granted by C#-centric frameworks and libraries).
The article you're looking at was written with F# 2.0 in mind - CLIMutable wasn't around yet and there was no way of using records for that.

Entity Framework datatype length

Is there a way to get the datatype length from an entity framework table?
I am needing to create a table in the database if the EF and DB are not in sync, so grab the info from EF to create a script to create the table.
EF is DB agnostic. You can call the underlying DB directly to ask about the Metadata. You can also for types that allow (decimal, string etc) specify the length you would like in code first scenarios. EF first does a comparison to check code and DB match. You can request/trigger migration.
Actually you can't because EF maps all the DB fields to primitive data types (C#). So the best solution for this is to think logically for each data types. e.g map string datatype to nvarchar[max], true/false to bit or int....etc etc

Get values in NotMapped property in model class Entity Framwork Code First using linq

I have the below scenario. I am using EF 5 Code first, MVC 4 on VS 2010. I am using the Unit of Work and Repository pattern for my project.
I am not sure if this is possible or not. Kindly suggest.
I have a model class representing a database table. In the model class, I have a property that is decorated as [NotMapped]. I have a Stored Proc that returns data, similar to the model class. However, when I get the data in a List from the SP, it does not contain value for the [NotMapped] column (SP returns data for the [NotMapped] column though). This may be logically correct with respect to EF.
All I want to know is, do we have a way to get data populated for the [NotMapped] column. I want to achieve, CRUD using LINQ (excluding R - Read).
I would recommend to create a separate complex type for the stored procedure results. Otherwise sooner or later you will find yourself writing code to distinguish between entities coming from the DbSet or from the stored procedure. When the come from the stored procedure they can't be used in joins, for example. Or checks whether or not the unmapped property is set.
A very dirty approach could be to have two different contexts. With code first it is possible to have different contexts with different mappings to the same types, with and without the column ignored (if you use fluent mapping, not with data annotations). But that only succeeds if you tell EF not to check the database schema, so using migrations is ruled out as well. I would not do it!! For the same reason as I mentioned above. I would hate to have a type with a property that sometimes is and sometimes isn't set.

Any decent resources on how to map complex POCO objects in EF 4.1?

So I heard L2S is going the way of the dodo bird. I am also finding out that if I use L2S, I will have to write multiple versions of the same code to target different schemas even if they vary slightly. I originally chose L2S because it was reliable and easy to learn, while EF 3 wasn't ready for public consumption at the time.
After reading lots of praises for EF 4.1, I thought I would do a feasibility test. I discovered that EF 4.1 is a beast to get your head around. It is mindnumblingly complex with hundreds of ways of doing the same thing. It seems to work fine if you're planning on using simple table-to-object mapped entities, but complex POCO object mapping has been a real PITA. There are no good tutorials and the few that exist are very rudimentary.
There are tons of blogs about learning the fundamentals about EF 4.1, but I have a feeling that they deliberately avoid advanced topics. Are there any good tutorials on more complex mapping scenarios? For instance, taking an existing POCO object and mapping it across several tables, or persisting a POCO object that is composed of other POCO objects? I keep hearing this is possible, but haven't found any examples.
Disclaimer: IMO EF 4.1 is best known for its Code-First approach. Most of the following links point to articles about doing stuff in code-first style. I'm not very familiar with DB-First or Model-First approaches.
I have learned many things from Mr. Manavi's blog. Especially, the Inheritance with code-first series was full of new stuff for me. This MSDN link has some valuable links/infos about different mapping scenarios too. Also, I have learned manu stuff by following or answering questions with entity-framework tags here on SO.
Whenever I want to try some new complex object mapping, I do my best (based on my knowledge about EF) to create the correct mappings; However sometimes, you face a dead end. That's why god created StackOverflow. :)
What do you mean by EFv4.1? Do you mean overhyped code-first / fluent-API? In such case live with a fact that it is mostly for simple mapping scenarios. It offers more then L2S but still very little in terms of advanced mappings.
The basic mapping available in EF follows basic rule: one table = one entity. Entity can be single class or composition of the main class representing the entity itself and helper classes for set of mapped fields (complex types).
The most advanced features you will get with EF fluent-API or designer are:
TPH inheritance - multiple tables in inheritance hierarchy mapped to the same table. Types are differed by special column called discriminator. Shared fields must be in parent class.
TPT inheritance - each type mapped to the separate table = basic type has one table and each derived type has one table as well. Shared fields must be defined in base type and thus in base table. Relation between base and derived table is one-to-one. Derived entities span multiple tables.
TPC inheritance - each class has separate table = shared fields must be defined in base type but each derived type has them in its own table.
Entity splitting - entity is split into two or more tables which are related by one-to-one relation. All parts of entity must exist.
Table splitting - table is split into two or more entities related with one-to-one relation.
Designer also offers
Conditional mapping - this is not real mapping. It is only hardcoded filter on mapping level where you select one or more fields to restrict records which are allowed for loading.
When using basic or more advanced features table can participate only in one mapping.
All these mapping techniques follow very strict rules. Your classes and tables must follow these rules to make them work. That means you cannot take arbitrary POCO and map it to multiple tables without satisfying those rules.
These rules can be avoided only when using EDMX and advanced approach with advanced skills = no fluent API and no designer but manual modifications of XML defining EDMX. Once you go this way you can use
Defining query - custom SQL query used to specify loading of new "entity". This is also approach natively used by EDMX and designer when mapping database view
Query view - custom ESQL query used to specify new "entity" from already mapped entities. It is more usable for predefined projections because in contrast to defining query it has some limitations (for example aggregations are not allowed).
Both these features allow you defining classes combined from multiple tables. The disadvantage of both these mapping techniques is that mapped result is read only. You must use stored procedures for persisting changes when using these techniques.