Entity Framework Inheritance - entity-framework

Have a scenario with a client's new crm where they have suppliers and clients and a supplier is also a client and vice versa. Table per hierarchy will only allow a person to only be one or the other, so I assume table per type would be better suited.
The db structure would be:
[Contact]
ContactId pk
Name
...
[Client]
ContactId pk / fk
VATNumber
...
[Supplier]
ContactId pk / fk
...
Anyone have any other suggestions or experience from a similar scenario?

Table per type will also assume one Contact is either a client or a supplier (this is clearer if you look at the generated SQL: eg. see "Inheritance with EF Code First CTP5: Part 2 – Table per Type (TPT)").
Instead I think you need to change your model to be Contact and Contact-Role with a one to many relationship. Contact-Role would have the Supplier and Client subtypes. The whole Contact-Role hierarchy could then be mapped as TPH or TPT.
This reflects an OO design where each client has one or more roles (inheritance, "is-a" releationship, will always be singular, you cannot have an object of abstract type client that is simultaneously both subtypes of client).

This cannot work unless you model it as three level inheritance which would require that either client is always supplier or supplier is always client. I guess that is not correct model in your application which means you cannot use inheritance.
You have to either use one-to-one (0..1-1) relations between contact-client and contact-supplier or you can simply place all properties to single table and add IsClient and IsSupplier bit columns - it is not very nice and it is less extensible but it is very easy to use. These two bit columns can be useful in case of relational representation as well.

Related

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?

Target/Source and owning/not owning entities

I'm a bit confused about this naming convention.
What is the difference between them and are target/source interchangeable with owning/not owning?
One thing in particular is hard to understand:
"The main difference between a OneToOne and a ManyToOne relationship in JPA is that a ManyToOne always contains a foreign key from the source object's table to the target object's table, where as a OneToOne relationship the foreign key may either be in the source object's table or the target object's table"
JPA wikibooks
I can't imagine such situation in uni one-to-one
Differences between them are a little confusing. You should practice a lot to understand very well.
At first, you should understand some terminology:
Role : In every relationship there are two entities that are related to one another, and each entity is said to play a role in the relationship.
Direction : Relationships can be unidirectional or bidirectional. For e.g.. a Person has an address is normally unidirectional whereas Employee working on a project is normally bidirectional. We will look at how to identify and define directionality while coming up with a Data Model.
In order to have relationships at all, there has to be a way to create, remove, and maintain them. The basic way this is done is by an entity having a relationship attribute that refers to its related entity in a way that identifies it as playing the other role of the relationship. It is often the case that the other entity, in turn, has an attribute that points back to the original entity. When each entity points to the other, the relationship is bidirectional. If only one entity has a pointer to the other, the relationship is said to be unidirectional. A relationship from an Employee to the Project that they work on would be bidirectional. The Employee should know its Project, and the Project should point to the Employee working on it. A UML model of this relationship is shown here. The arrows going in both directions indicate the bidirectionality of the relationship (Form this book >> Pro JPA 2)
Then dive into this link (archived from the original)
I'd like to comment only the links, but I need 50 reputation

Entity Framework Code First unique constraint across multiple tables

So I'm creating a database model using Entity Framework's Code First paradigm and I'm trying to create two tables (Players and Teams) that must share a uniqueness constraint regarding their primary key.
For example, I have 3 Players with Ids "1", "2" and "3" and when I try to create a Team with Id "2", the system should validate uniqueness and fail because there already exists a Player with Id "2".
Is this possible with data annotations? Both these entities share a common Interface called IParticipant if that helps!
Txs in advance lads!
The scenario you are describing here isn't really ideal. This isn't really a restriction on Entity Framework; it's more a restriction on the database stack. By default, the Id primary key is an Identity column, and SQL itself isn't really supportive of the idea of "shared" Identity columns. You can disable Identity and manage the Id properties yourself, but then Entity Framework cannot automatically build navigation properties for your entities.
The best option here is to use one single participant table, in a technique called "Table Per Hierarchy", or TPH. Entity Framework can manage the single table using an internal discriminator column. Shared properties can be put into the base class, and non-shared properties can be put on the individual classes, which Entity Framework will composite into a single large table in the DB. The main drawback to this strategy is that columns for non-shared properties will automatically be nullable in the database. This article describes this scenario very well.
The more I try to come up with a solution, I realize that this is an example of the XY Problem. There is not really a good solution to this question, because this question is already a proposed solution. There is a problem here that has led you to create an Interface which you suggest requires the entities which are using the interface to have a unique Id. This really sounds like an issue with the design of the Interface itself, as Interfaces should be agnostic to the entity they are applied to. Perhaps providing some code and showing what your problem actually is would be helpful, since the proposed solution you are asking how to implement here isn't really practical.

How to implement different types of a class: inheritance, interface or class property?

I need to implement the following but I'm not shure what the best way is:
I'm creating a message functionality for an MVC app.
There are two types of messages:
Public messages
Private messages
The only difference is that public messages have a ValidFrom and ValidTo date field. I have tried the following:
Method 1, interface
IMessage interface. Two classes PrivateMessage and PublicMessage that implements the interface. PublicMessage has the two extra properties. Mapped it to two different tables with entity framework.
Method 2, inheritance
Create a message base class that has all the fields. Create two classes that inherit the base class. Can map the message class to the db so I only have one table to keep the records. I cannot map an interface with EF Code First it seems.
Method 3, Enum property to set what type of message
public enum MessageType
{
Public = 1,
Private = 2,
}
I just have one Message Class, but add a field to show what type of message it is. Maps easily to one table, and easy to search for messages of type "Public". I have to make a mini wrapper around the enum becouse EF wont create a field in the db for it though.
Is really the two property fields enough to justify two different classes? Searching two database tables for unread messages is a bit ineffective?
Is there a right way to do this?
I use Entity Framework Code First 4.3.
ORM frameworks usually solve the inheritance problem in three ways :
1.One table for all objects: in this approach there's one table and each concrete class will use the same table . A discriminator will be used to find out which record is related to which class.
2.One table for each concrete object: for each concrete object there will be a corresponding table in the database and each object has its own map .The framework doesn't know that these objects are part of a inheritance hierarchy.(no discriminator is needed)
3.One table for each object (concrete or abstract):in this approach shared data is stored in a table that's map to the base abstract class and each concrete object will have a separated table storing its own data and there's a one to one relationship between this table and its parent table.Again a discriminator is needed in parent table to show the framework which records belong to which object.
in first approach number of tables is minimum (just one table) but it has all the fields of all objects . thus all uncommon fields should be nullable and can accpet null.
in second shared data is distributed among many tables but each table is in control of its own fields thus there's no need to have some unnecessary null values.
The third approach has the most number of tables the shared data is stored in one place and again there's no unnecessary null values all over the place.
It seems that according to your scenario the first approach is the best because the difference between two objects is very small (only two fields) and having some null values in your table is tolerable and it's better than having two or three tables in your database,
You can accomplish this is many ways, as it seems that you are experimenting with. So...
1) You can have 1 entity Message that contains all fields and an extra column IsPublic
2) You can have 2 entities PublicMessage and PrivateMessage persisted in 2 tables
3) You can have TPT or TPH inheritance model where you have Message as a base class of PublicMessage and PrivateMessage
The question of which to use is more about what business problem you are trying to solve. You mention that searching two tables is inefficient. So, I assume that you have a view to build where a single person can see both private and public messages. If you can, it is better to optimize after you have a performance issue (and data to support it).
It is interesting that the public messages have a to and from date. This suggests that the life cycle of the two entities differ. This could indicate that they need to be managed separately.
With all those assumptions, I would opt for the simple and make them to separate entities. Making two queries for unread messages is not the end of the world.

ADO.NET Entity Framework: Can I have multiple entity types for the same row

I have a base class Participants inherited by Artist, Author and TextWriter.
I have only one table in the data store:
Participants {
ID,
FirstName,
LastName,
IsArtist,
IsAuthor,
IsTextWriter,
}
The idea is to have a class for all the roles that a participant can have.
I've managed to create the edmx file but when I try to get an Participant (as Artist) that is also an Author I receive the following error:
All objects in the EntitySet 'Participants' must have unique primary keys. However, an instance of type 'Artist' and an instance of type 'Author' both have the same primary key value, 'EntitySet=Participants;ID=1'.
Thank you
Yes, this is possible. What you're asking for is "table per hierarchy" inheritance. Your table needs to contain any "discriminator column" which identifies the type of each row.
However, no record for one person can have more than one concrete type when materialized (read from the DB), because an object can only have one type. I've written about this issue before:
One of the mental barriers that you have to get over when designing a good object relational mapping is the tendency to think primarily in object oriented terms, or relational terms, whichever suits your personality. A good object relational mapping, though, incorporates both a good object model and a good relational model. For example, let’s say you have a database with a table for People, and related tables for Employees and Customers. A single person might have a record in all three tables. Now, from a strictly relational point of view, you could construct a database VIEW for employees and another one for customers, both of which incorporate information from the People table. When using a one VIEW or the other, you can temporarily think of an individual person as "just" an Employee or "just" a Customer, even though you know that they are both. So someone coming from this worldview might be tempted to do an OO mapping where Employee and Customer are both (direct) subclasses of Person. But this doesn’t work with the data we have; since a single person has both employee and customer records (and since no Person instance can be of the concrete subtype Employee and Customer simultaneously), the OO relationship between Person and Employee needs to be composition rather than inheritance, and similarly for Person and Customer.
If "Bob" is a Participant who is both an Artist and an Author, then he cannot be of type, say, Artist and Author at the same time, unless one is a supertype of the other. Either Artist and Author should have a subtype relationship with the other or you should use aggregation rather than inheritance to relate Participant with Artist and Author. An instance of an object can have only one concrete type; this does not change because you store it to the DB.