Entity Framework Code First mapping situation - c#

I'm trying to port an existing application (using pure ADO.Net) to a new one using EF 4.3 Code First. It is worth mentioning that this is the first time I'm using EF.
Basically I have a suppliers table but with two specialization tables with attributes specific to each of the two types of suppliers.
Here is what the existing database looks like:
create table Supplier(
id_supplier int not null identity
--Bunch of other attributes
);
create table Individual(
id_individual int not null --not identity, gets the same value as the Supplier table
--Attributes specific to individuals
);
alter table Individual add constraint fk_individual_supplier
foreign key(id_individual) references Supplier(id_supplier);
create table Corporation(
id_corporation int not null --not identity, gets the same value as the Supplier table
--Attributes specific to corporations
);
alter table Corporation add constraint fk_corporation_supplier
foreign key(id_corporation) references Supplier(id_supplier);
So, as the tables show, a supplier can be either an individual or a corporation.
The existing application is like this:
abstract class Supplier with its attributes
class Individual deriving from Supplier with its additional attributes
class Corporation deriving from Supplier with its additional attributes
The Ado.Net code currently works receiving Supplier objects, generating records on Individual table if the object passed is of Individual type or Corporation table if the object passed is of Corporation type.
So, every record on Supplier will have a matching one on either Individual or Corporation. Also, Individual and Corporation tables does not have foreign keys to any other table of the database. Instead, the relations are all with the Supplier table. The table generating the ID is Supplier.
How can I map this with Code First?
At first I thought about keeping my structure, I mean, Supplier abstract class and Individual and Corporation deriving from that. Because I need Entity to insert on Supplier table first (generate identity field), it seems that both Individual and Corporation model classes would be mapped to Supplier table.
But how would it be possible for it to receive the abstract class and insert on either one of the specialization tables depending on the type? I don't think this is possible without custom SQL which makes me think my approach is wrong.
Thanks in advance for helping.

This sounds like "table per type" inheritance (TPT). With TPT there is a base table with columns that are common for all derived types and tables per derived types with type-specific columns. Entity framework supports this model. See this excellent blog post for examples how to do it both with data annotations and fluent mapping.

Related

Entity Framework Code First with Dynamics Navision Tables

I have a project where I need to design a code first entity system with an existing database. These existing tables in the database are not just any tables, they were being created by Microsoft's ERP tool "Dynamics Navision". The Navision tool holds different company information and creates different tables per company. Let's assume there are 3 types of tables;
TableX
TableY
TableZ
And also there are 3 different companies;
CompanyA
CompanyB
CompanyC
The tool created 9 different tables from above combinations. It simply duplicates all of the tables and adds a prefix with the company name to the table names. At the end, our database looks like this;
CompanyA$TableX
CompanyA$TableY
CompanyA$TableZ
CompanyB$TableX
CompanyB$TableY
CompanyB$TableZ
CompanyC$TableX
CompanyC$TableY
CompanyC$TableZ
What Did I do so far?
So as you can see, there is an opportunity to simplify this architecture at the Entity Framework side. To achieve this, I created 3 entity classes for TableA, TableB, TableC and at the run time, I let the user to choose a company and according to the chosen company, I reflected my entity class with a custom TableAttribute where the table name prefixed with the company name. I am not going to give details on how I achieved it right now(but you can find implementation details on this article: LINK) but so far so good and I have applied all of the previous steps successfully and I managed to be dynamic on table names with the chosen company. However, there is another problem.
What is my question?
The problem is, even though I managed to create a system where I can change the entity class' table name attribute at the runtime and access to the target companies tables, there were no guarantee that duplicated tables with different company name prefixes are sharing %100 same inner field architecture. For example, CompanyA$TableX can have 5 fields while CompanyB$TableX has 6 fields where the first 5 fields are the same with CompanyA$TableX's fields but the last 1 field is extra. Let's also visualize it;
CompanyA$TableX's table fields;
ID
Name
Surname
Adress
PhoneNumber
CompanyB$TableX's table fields;
ID
Name
Surname
Adress
PhoneNumber
EMail
As you see, the Email field is the extra however the table names are the same(TableX), only the company differs and in my system, they share the same entity class and the company name determined at the run time as I mentioned before.
So, I want to know about how can I achieve to be dynamic on this. How I can have only one entity class but be dynamic in the fields of this class according to the chosen company. I want to know if it is possible technically and if it is, how to implement it. Thanks in advance.
What you are saying about Nav is not true. It is not possible to create the same table in Nav that will have different structure per company. Even the modern extension architecture will not give you that kind of result.

Catchall Table with Entity Framework

I am extracting data from a set of JSON files into an MS T-SQL database using Entity Framework.
There are a bunch of sub-collections in the JSON files (counted 20 so far) that all follow the pattern "CollectionName":{"Code":"SomeCode","Description":"Some Description"}.
For example: "Country":{"Code":"GB","Description":"Great Britain"} or "Language":{"Code":"FR","Description":"French"}
The code I am working with uses this pattern: an Entity is created called CollectionName, which maps to a table with PK, Code & Description columns and then another Entity called SourceCollection (ex: PersonLanguage) which maps to a Bridge Table having the Source PK & CollectionName PK for each. When you have a lot of these little sub-collections, that is a lot of tables.
As a T-SQL programmer, I have solved similar problems in the past by creating a 'catchall table' that has a PK, a CollectionName Column, and then a Code & Description column as above. So all these little collections reside in a single table, with a foreign key pointer in the source table.
I cannot find any description of how to implement this in Entity Framework, can anyone point me in the right direction with either a link or some sample code?
The pattern you're describing is sometimes called a "common lookup table" and is generally considered an anti-pattern for reasons of referentially integrity and constraints.
Merits of the design decision aside, you have two options:
A) Create a new EF entity with properties for Id, CollectionName, Code and Description and map your existing classes and data to that entity for CRUD operations via some pattern such as Repository.
B) Use EF type inheritance with table-per-hierarchy mapping and allow EF to map multiple entities to the same table. The abstract parent type would have Id, Code and Description properties. EF will automatically create a discriminator column that serves the same purpose as CollectionName.

Entity Framework 5 Enum Naming

I am using EF 5 with migrations and code first. It all works rather nicely, but there are some issues/questions I would like to resolve.
Let's start with a simple example. Lets say I have a User table and a user type table. The user type table is an enum/lookup table in my app. So the user table has a UserTypeId column and a foreign key ref etc to UserType. In my poco, I have a property called UserType which has the enum type.
To add the initial values to the UserType table (or add/change values later) and to create the table in the initial migrator etc. I need a UserType table poco to represent the actual table in the database and to use in the map files. I mapped the UserType property in the User poco to UserTypeId in the UserType poco. So now I have a poco for code first/migrations/context mapping etc and I have an enum. Can't have the same name for both, so do I have a poco called UserType and something else for the enum or have the poco for UserType be UserTypeTable or something?
More importantly however, am I missing some key element in how code first works? I tried the example above, ran Add-Migration and it does not add the lookup table for the enum.
If I understood properly your questions and what you're confused about,
Enums support has nothing to do with lookup tables on the Db side.
Enums are simply allowing you to have properties in your classes that are Enum-s and that is translated into 'int'-s basically - so there is nothing much else in there.
For more info you might wanna look at this video from Julie Lerman on Enum-s support
hope this helps
In my experience the enum is more important to your code than the lookup class so give it the proper name. I would also keep the look up class isolated without any relationship to the User in my Model. If it trully is only for lookup, then you don't need it hanging off of your User. Your enum with a DescriptionAttribute can fulfill the lookup in your code.
UserTypeLookup might be a good name since that sounds like what you will be using it for. Then you can use that class to maintain the table.
Assuming you don't map the relationship between UserTypeLookup and User in ef code first, the only thing you should need to create in the DB manually is the foriegn key relationship between the UserType column in your User table and the PK from the UserTypeLookup table. UserTypeLookup can still be an entity and EF should still generate the DB table for it even if you don't setup any relationships for it.

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! :-)

Entity Framework Model Multiple Table to Single Entity

I've two tables named Modules and Privileges which are related by a foreign key relationship as shown below:
(source: baburajpb at sites.google.com)
I'd like to model Module and Privilege by adding ModuleName to Privilege. Later I'd be interested in creating a derived class (Menu in the illustration) from Privilege by adding a discriminating condition on ModuleName. Is this possible using Entity Framework?
Can you map multiple tables to a single entity type? Sure, that is supported. However, you cannot use a mapped field of the table (ModuleName) as a discriminator column for table per hierarchy mapping. The discriminator column must be used as a discriminator alone, and must not be mapped into your client schema.

Categories

Resources