One Entity for multiple similar tables - entity-framework

have two tables in database.
They have completely the same columns, only the difference between them - they have different names.
Lets say i have TableSea with column s Id and Name and TableOcean with the same columns Id and Name.
I want to use EF 4 to be able CRUD operations, i am also want to use stored procs mapping for insert update and delete operations.
I am already created POCO entity for first table and i did create stored procedures and map them to entity model. All working well.
How make it work with two tables without create a new entity for second table?

AFAIK, you can't, and you definitely shouldn't!
If you have two identical database tables, then this means one of the following:
The two tables mirror closely
related concepts (like Sea and Ocean
in your example).
The two tables
mirror different concepts which only
accidentally have the same
properties.
Depending on which scenario is closer to reality, you have these two design options:
Merge the two tables and add a
Type property (column), then map
it to one entity type. You might
have different subclasses to
differentiate between types, or you
may go with an additional Type
property - whichever fits better for
you.
Have two tables. Which means: there are two different concepts. Consequently, this has to be mirrored by two different entities in the business model.
In any case, having an entity table in the database means having an entity class in the business model. If there's no such 1:1 - mapping, then clearly something is wrong with the design!
Thomas

Related

When to use an owned entity types vs just creating a foreign key or adding the columns directly to the table?

I was reading about owned entity types here https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities#feedback and I was wondering when I would use that. Especially when using .ToTable(); although I am not sure if ToTable creates a relationship with keys.
I read the entire article so I understand that it essentially forces you to access the data via nav properties and prevents the owned table from being treated as an entity. They also say Include() is not needed and the data comes down with every query for the parent table so its not like you are reducing the amount of data that comes back.
So whats the point exactly? Also whats the point of "table splitting"?
It takes the place of Complex types with the option to set it up like a 1-1 relationship /w ToTable while automatically eager-loaded. This would use the same PK in both tables, same as 1-1.
The point Table-splitting would be that you want an object model that is normalized, where the table structure is not. This would fit scenarios where you have an existing table structure and want to split off related pieces of that data into sub-entities associated with the main entity. With the ToTable option, it would be similar to a 1-1 relationship, but automatically eager-loaded. However when considering the reasons to use a 1-1 relationship I would consider this option a bad choice.
The common reasons for using it in normal 1-1 relationships would include:
Splitting off expensive to load, rarely used data. (images, binary, memo)
Encapsulating data particular to a single application off of a common entity. i.e. if I have a "Customer" which is used by a billing system vs. a CRM I might have "CustomerBillingData" and "CustomerCRMData" owned by "Customer" rather than an inherited BillingCustomer / CRMCustomer. As there is a "single" customer that may serve one or both systems. Billing doesn't care about CRM data, CRM doesn't care about Billing. If all data is in "Customer" then both systems potentially need to be updated, and I cannot rely on constraints when the data is optional to the other system. By using composition I can enforce required data for a particular system.
In neither of these cases would I want to use table-splitting or anything that automatically eager-loads, so Owned Types /w ToTable would not replace 1-1 relationships by any stretch. It's essentially a more strict version of complex types, I'd say it's strictly used for entity organization. Not something I'd admit to wanting to use very often.

Null values in relational database

I'm new in PostgreSQL(still learning)
I'm trying to create a relational database for a venue.
In my table(still in UNF) I have attribute to store the client's name, phone, email.
The problem is that the client will give maybe 2 or 1 info on him. So I will always have null values.
Sometimes I can get all the client's values(for the 3 attribute)
How am i supposed to deal with this in the normalization process?
Do I need to separate the tables in other relation. If so 3 relations is not too much?
For every attribute that should be there once, use a column in the main table. "Should" indicates it might be missing / unknown, too. That's a NULL value then. If the attribute must be there, define the column NOT NULL.
Attributes where there can be multiple distinct instances, especially if the maximum number is uncertain, create a separate table in a one-to-many relationship.
Store (non-trivial) attributes that can be used in many rows of the main table, in a separate table in a many-to-one relationship.
And attributes that can be linked multiple times on either side are best implemented in a many-to-many relationship.
Referential integrity is enforced with foreign key constraints.
It's not nearly as complex as reality, but the point is to establish a logically valid model that can keep up with reality.
Read basics about database normalization.
Detailed code example with explanation and links for n:m relationship:
How to implement a many-to-many relationship in PostgreSQL?

Is it possible to associate entities in different models?

We have one DB with many tables. We decided to create different models instead of just one containing all the tables.
We'd now need to associate an Entity (table) in ModelA with an Entity (table) in ModelB. Obviously at DB level this is possible (a simple foreign key) but it looks like it is not at model level.
Suggestions?
Your database is composed of one big model with many tables and relationships
But in your application if you are going to split it into two models then there is a lot of chance of having "Entities" that will be needed in different models.
You can create two different entities instead each representing what is needed from the table in each particular model and map each entity to the same table in Entity Framework
See the image below
The black boxes are your tables, the red and blue are your entites.
As you can see the whole database is related but your ModelA includes only some fields on the common table, while Model B includes its own set of fields from the common table.

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.

EF CodeFirst: Mapping entities (one-many) to the same table

Lets say I have Customer, Order, OrderDetail classes in the business layer (It's a simplified version of my problem).
I have also an old (existing) database that has one global table where every row of the table contains the information of Customers-Orders-OrderDetails; for example:
CustomerID, CompanyName,Fax,OrderID, OrderDate,ProductID,UnitPrice,Quantity
(in this way there are duplicated information of a Customer in different rows).
In the future I'll have a new database (with different table Customers, Orders, OrderDetails), and I want to use the same program.
I want to use EF CodeFirst to mapping to the old database and in the future to the new database
Which is the best solution?
Design a business layer with a global class that contains the information of Customers-Orders-OrderDetails. So the mapping of this class
with the old database using EF4 in the data layer is trivial.
In the future I'll modify both business layer and data layer for the new database.
Design a business layer with Customers, Orders, OrderDetails classes. In this case is it possible to map these classes to the global table of the old database? How ? (the problem is that the Customer-Order is one to many).
In the future I'll modify only data layer for mapping the new database.
This will work for now and later you will have to modify everything working with a global class - it can be a lot of work.
It is not possible to map one table to three entities where two have one-to-many relation between them with EF.
Use third approach. Load one class as described in first approach but immediately convert result to three classes from the second approach. The reverse operation will be done in case of persisting changes. Wrap this code in single place - repository. Your application will use three classes and it will not have any knowledge about the way how they are persisted. Once you change the database you will only remove additional conversions from the repository and work directly with Customer, Order, OrderDetail loaded and persisted by EF.