Do I really need an identity field on Bridge Tables? - postgresql

Do I really need an extra identity field say called id on a bridge table? For primary tables I set an id and have it start incrementing from 0. But not sure about bridge tables.
Example:
user
user_id (identity)
name
user_communities
id (identity) - do I even need this??
user_id
community_id
communities
community_id (identity)
name

No, you don't need an additional generated primary key on a bridge table - at least not if (user_id, community_id) is the primary key.
You would only need it in case you would allow a user to participate in the same community multiple times, e.g. with different roles.

Your relationship links two entities, thus you have the ids of the two entities in it. In that case the id in your bridge table is unnecessary.
But, although rarer, you could also have higher order relationships which connect two relationships or a relationship with other entities. Say, for example, you want to qualify a relationship with a set of properties (the strength of the relationship, its participants, etc), you could have a relationship properties table that links to the relationship (thus you would need its id) to a set of name-values pairs. You could even have a bridge table between two different bridge tables to connect them and assign certain properties to the connection (which relationship has priority over the other, e.g.)

Related

Multiple Entities need an address in database

I have two entities customers and stores and they both need adresses should i do different adresses tables for each entity or use one for both with 2 different foreign keys but the the 2nd case i will probably have a lot of null values in my table since only one of both will be filled.
If the fields of the address table are similar for each entity I would use one address table with foreign keys.
If there are lots of specifics fields for customers and stores in your address then i would use 1 table for each...

Foreign key from events table 1-1 0r many?

I'm likely overthinking a problem here and may well get downvoted but I'm prepared to take the hit. I'm building my first schema in a data warehouse.
2 tables: events and contacts:
events(id(pk), cid, other, fields, here)
contacts(id (pk), cid(fk), other, fields, here)
Someone visits our website and registers. A line item is generated in events column "id" and a "cid" for contacts is generated. A new record is added to contacts.
I have two questions:
Can I make the primary key of contacts cid? Thus the primary key is also a foreign key?
I'm using MySQL Workbench to create the schema. When I create the contacts table I am able to set the foreign key of cid and the cardinality as either 1-1 or 1-many. From the point of view of contacts table, is the relationship 1-1 or to many? There will only ever be 1 cid record in contacts but if that user does multiple things (like receive an email from us etc) they will appear multiple times in events table. So, logically 1-many. But when creating this in Workbench the relation line appears as though it's a 1-many relation with the many part being at contacts, not the other way around as desired. It should be the other way around?
What is the relationship between events.cid and contacts.cid?
If a user's registration results in a single contact_ record while each user visit to the web site (each Session started) results in an event_ record belonging to that user’s contact_ record, then you have a One-To-Many relationship.
`contact_` = parent table (the One)
`event_` = child table (the Many)
Notice how I boiled down that relationship into a single sentence. That should be your goal when doing analysis work to determine table structure.
Relationships are almost always defined as a link from a primary key on parent table to a foreign key on a child table.
How you define the primary key is up to you. First decide whether you want a natural key or a surrogate key. In my experience a natural key never works out as the values always eventually change.
If using a surrogate key, decide what type. The usual choices are an integer tied to an automatically incrementing sequence generator, or a UUID. If ever federating data with other databases or systems then UUID is the way to go. If using an integer, decide on size, with 32-bit integers handling a total of 2-4 billion records. A 64-bit integer can track 18 quintillion records.
The foreign key in child table is simply a copy of its assigned parent’s primary key value. So the foreign key must have same data type as that parent primary key.
If a particular parent record owns multiple records in the child table, each of those child records will carry a copy of that parent’s primary key. So if the user Susan has five events, her primary key value appears once in the contact_ table and that same value appears five times in the event_ table stored in the foreign key column.
If cid uniquely identifies each contact_ record amongst all the other contact_ records, then you have a primary key. No need to define another.

Why we need to specify cardinality in cognos/hibernate but not in oracle

When we specify a foregin key relationship in oracle, we do not need to say whether relationship is 1 to 1, 1 to many etc. But when we specify a relationship in the cognos framework manager, why we need to specify 1 to 1, 1 to many etc?
Also, unrelated but just curious, the same is the behavior in a ORM tool like Hibernate.
Is the specification only for optmisation purposes?
My other question is what is th effect of specifying a wrong cardinality relationship? i,e, I specify a 1 to 1 relationship where it is actually 1 to many. What is the effect i am risking?
You do declare the relationships in Oracle, the nature of the relationship is implicit in the way that it is declared to Oracle, e.g.:
CONSTRAINT fk FOREIGN KEY (id) REFERENCES parent_table (id)
implies that there is a 1:M relationship between the parent table and this table.
If, in addition, there was a unique constraint on the child table, e.g.:
CONSTRAINT uk UNIQUE (id)
implies that the relationship is 1:1.
From Cognos documentation:
IBM® Cognos® software uses the cardinality of a relationship in the following ways:
to avoid double-counting fact data
to support loop joins that are common in star schema models
to optimize access to the underlying data source system
to identify query subjects that behave as facts or dimensions
For further details, look here:
Framework Manager Cardinality

Entity Framework 4 - Use a single mapping table for all many-to-many relations

I would like to map all many-to-may relations through a single table in my database.
Meaning that I have numerous tables (entities) that have various many-to-many relations. Instead of having a separate mapping table for every relation I would like to use one "master mapping" table having to columns: End1Id & End2Id.
Don't ask why ;) It's required by my customer...
How would I set this up in the model designer, or do I have to edit the edmx xml directly....or is it just not possible?
Thanx for your help!
In such a scenario you can't have explicit foreign keys, because a table like this normally has at least three rows:
PK of table 1
PK of table 2
Type of mapping, which specifies the exact tables to use.
Because of that, you can just create a table in EF, but it will also have no connections to other tables and you will have to do the joins manually.
You would need to set this Master Mappings table manually. The designer doesn't do it for you automatically.
However - if denormalized entities are what you are looking for, better have those denormalized in DB level rather than in EF/code level.

Entity Framework and multi-tenancy database design

I am looking at multi-tenancy database schema design for an SaaS concept. It will be ASP.NET MVC -> EF, but that isn't so important.
Below you can see an example database schema (the Tenant being the Company). The CompanyId is replicated throughout the schema and the primary key has been placed on both the natural key, plus the tenant Id.
Plugging this schema into the Entity Framework gives the following errors when I add the tables into the Entity Model file (Model1.edmx):
The relationship 'FK_Order_Customer' uses the set of foreign keys '{CustomerId, CompanyId}' that are partially contained in the set of primary keys '{OrderId, CompanyId}' of the table 'Order'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The relationship 'FK_OrderLine_Customer' uses the set of foreign keys '{CustomerId, CompanyId}' that are partially contained in the set of primary keys '{OrderLineId, CompanyId}' of the table 'OrderLine'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The relationship 'FK_OrderLine_Order' uses the set of foreign keys '{OrderId, CompanyId}' that are partially contained in the set of primary keys '{OrderLineId, CompanyId}' of the table 'OrderLine'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The relationship 'FK_Order_Customer' uses the set of foreign keys '{CustomerId, CompanyId}' that are partially contained in the set of primary keys '{OrderId, CompanyId}' of the table 'Order'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The relationship 'FK_OrderLine_Customer' uses the set of foreign keys '{CustomerId, CompanyId}' that are partially contained in the set of primary keys '{OrderLineId, CompanyId}' of the table 'OrderLine'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The relationship 'FK_OrderLine_Order' uses the set of foreign keys '{OrderId, CompanyId}' that are partially contained in the set of primary keys '{OrderLineId, CompanyId}' of the table 'OrderLine'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The relationship 'FK_OrderLine_Product' uses the set of foreign keys '{ProductId, CompanyId}' that are partially contained in the set of primary keys '{OrderLineId, CompanyId}' of the table 'OrderLine'. The set of foreign keys must be fully contained in the set of primary keys, or fully not contained in the set of primary keys to be mapped to a model.
The question is in two parts:
Is my database design incorrect? Should I refrain from these compound primary keys? I'm questioning my sanity regarding the fundamental schema design (frazzled brain syndrome). Please feel free to suggest the 'idealized' schema.
Alternatively, if the database design is correct, then is EF unable to match the keys because it perceives these foreign keys as a potential mis-configured 1:1 relationships (incorrectly)? In which case, is this an EF bug and how can I work around it?
On a quick scan of EF's error messages, it clearly doesn't like the way you're setting up compound keys, and I think it's probably nudging you in the right direction. Give some thought again to what makes your primary keys unique. Is the OrderID alone not unique, without a CompanyID? Is a ProductID not unique, without a CompanyID? An OrderLine certainly should be unique without a CompanyID, since an OrderLine should be associated only with a single Order.
If you truly need the CompanyID for all of these, which probably means that the company in question is supplying you with ProductID and OrderID, then you might want to go a different direction, and generate your own primary keys that are not intrinsic to the data. Simply set up an auto-increment column for your primary key, and let these be the internal OrderID, OrderLineID, ProductID, CompanyID, etc. At that point, the OrderLine won't need the customer's OrderID or CompanyID; the foreign key reference to the Order would be its starting point. (And the CustomerID should never be an attribute of an order line; it's an attribute of the order, not the order line.)
Compound keys are just messy. Try designing the model without them, and see if it simplifies things.
I think that the error is not in the design.
Is not in the EF.
Is in Sql Server relations.
Read the EF message:
The relationship 'FK_Order_Customer'
uses the set of foreign keys
'{CustomerId, CompanyId}' that are
partially contained in the set of
primary keys '{OrderId, CompanyId}' of
the table 'Order'. The set of foreign
keys must be fully contained in the
set of primary keys, or fully not
contained in the set of primary keys
to be mapped to a model.
ERROR
Actualy the relation betwen Order and Customer use only one field (probably you dragged with the mouse the field "CustomerId" from teh Order table to the "Id" of the Customer table)
SOLUTION
Right click on the wire that connect Order and Customer and in the relation add also the CompanyId
PS: The design is correct.
Putting the CompanyId in each table is rith solution in multi-tenant architecture because help to scale (usualy always want to select only records from the loggedIn company).
I think storing the company number in each of the tables is hurting you more than helping. I can understand why you want to do this (as the programmer/dba you can just go into any table and 'see' what data belongs to who which is comforting), but it is getting in the way of you setting up the database the way it should be.
Avoid the compound keys and your design gets a whole lot simpler.
If you have to absolutely add CompanyID column to each table, add it as a regular column and not a composite Key. Composite key is mostly used when you have to implement many to many relationship.
As someone mentioned also create a Non-clustered Index on CompanyID so joins to the Company table are benefitted.
Thanks!
First: like others said, when referencing a foreign key, use the whole primary key in the other table (ie. both fields).
Second, I cannot imagine not using a CompanyID column in most tables in a serious application. Orderdetail might perhaps be an exception in this case (also global lookup tables perhaps, unless they are tenant dependant). Thing is, you cannot do any safe sort of free form search on a table without either adding the CompanyID, or doing JOINs up until the point you reach a table which has that column. The latter one obviously costs performance. Perhaps in this case you could make an exception for orderdetail and only search in the joined version (only two tables). Then again, its not really consistent.
Also regarding making a it a compound key or not: its possible, but opens up the possibility that a bug writes information incorrectly (into non existent, or other people's administrations) for the duration of the bug. Try to fix that in production, not to mention explain it to customers why there are seeing their competitors orders in their system.