Entity Framework 6 - Many-to-Many Table with Additional Information - sql-server

Seems I am not allowed to post images, so let me describe the image. It is a SQL table diagram showing the relationships between 4 tables. The Tables are:
People
Id
FirstName
LastName
PhoneNumbers
Id
Number
PhoneNumberTypes
Id
Name
Description
PeoplePhoneNumbers
PersonId
PhoneNumberTypeId
PhoneNumberId
The two main tables are People and PhoneNumbers. There is also a PhoneNumberTypes that describes the type of PhoneNumber (Home, Work, etc).
The PeoplePhoneNumbers table serves as a Many-To-Many relationship table between People and PhoneNumbers. However it also connects to PhoneNumberTypes to describe the relationship.
I have been trying to figure out how to handle this Entity Framework because EF does not allow you to add additional information to the Association(Many-To-Many) Table.
Besides the PhoneNumberType info, I also find that their are additional data pieces I need to record in the Association Table like "Start Date", "End Date", etc.
The only solution I have come up with so far is to create an entity in EF that combines the fields in PhoneNumberTypes, PhoneNumbers and PeoplePhoneNumbers into a single entity. Then use SQL stored procedures for CRUD operations against it.
I would prefer a more EF centric solution. Does anyone know of one?

PhoneNumberTypes should not be linked to PeoplePhoneNumbers. Let PeoplePhoneNumbers be what it is and only a junction table. PhoneNumberTypes should be linked to PhoneNumbers. EF should be able to create this setup by convention. Additional information describing phone number should also be linked off of PhoneNumbers. This design adheres to more Domain Driven Design (DDD) principles and also generates a better database design as well.

Related

Differentiation between 'Entity' and 'Table'

Can someone tell me the easy way to explain the differentiation between an entity and a table in database?
Entity is a logical concept of relational database model. And table is used to express it, but there is a slight difference. Table expresses not only entities, but also relations.
For example, assume that you want to make a database of projects and employees of a company. Entity is a unit of information that has meanings by itself. In this case, there will be two entities - "Project" and "Employee". Each entity has its own attributes.
In relational DB model, there is another idea, 'relation'. If employees participate in several projects, then we can say that there is a relation with a name 'works_on'.
Sometimes, relation can have its own attribute. In this case, 'works_on' relation can have attribute 'start_date' and so on. And if this relation is M:N relation(Like this case: In project 1, there are 5 employees. Employee A works on two projects.), then you have to make an extra table to express this relation. (If you don't make an extra table when the relation is M:N, then you have to insert too many duplicated rows into both 'Project' and 'Employee' table.)
CREATE TABLE works_on(
employee,
project_id,
start_date
)
An entity resides in a table, it is a single set of information, i.e: if you have a database of employees, then an employee is an entity. A table is a group of fields with certain parameters.
Basically everything is stored in a table, entities goes into tables.
In a relational database the concept is the same. An entity is a table.
In OOP (Oriented Object Programming) there is a nice article in Oracle docs:
In general terms, entity objects encapsulate the business policy and
data for
the logical structure of the business, such as product lines,
departments, sales, and regions
business documents, such as invoices, change orders, and service
requests
physical items, such as warehouses, employees, and equipment
Another way of looking at it is that an entity object stores the
business logic and column information for a database table (or view,
synonym, or snapshot). An entity object caches data from a database
and provides an object-oriented representation of it.
Depending on how you want to work, you can create entity objects from
existing database tables (reverse generation) or define entity objects
and use them to create database tables (forward generation).
There is little difference between an entity and a table, but first we should define the concepts of “tuple” and “attribute”. I want to express those concepts with a table.
Here is an example of a table. As you can see it has some columns. Each column represents an attribute and each line represents a tuple(row). This is the employee table. In this example, the table is being used for representing an entity which is employee. However, if we create a new table named superior to specify the superiority relationship between those employees, it would be a table that represents a relation. In summary, we can use tables for representing both the entities and relations so entities and tables are not the same.

Cakephp workaround for model inheritance relationship

From my understanding, cakephp doesn't support database inheritance relationship. However, I want to create a database with different type of Users.
In this case, there are three types of Users: Seller, Customer, and Administrator. Every users should have basic User information such as password, username, etc.
However, each types of users will have its own unique set of datas. For example, seller may have inventory_id while customer may have something like delivery_address, etc.
I have been thinking of creating a workaround to this problem without destroying cakephp convention. I was going to create three additional foreign keys, admin_id, seller_id and customer_id, inside User table, which links to other table. However, knowing that this is an IS-A relationship not HAS-A, I would have to make sure that two of the ids are NULL value. Therefore, this workaround seems ugly to me..
Is there any other simpler, better approach?
For this type of database structure I would probably look at adopting an Entity-Attribute-Value model. This would mean your customer may have a delivery_address and your user may have an inventory_id but as far as your relationship in Cake is concerned your both your user and customer would just have an attribute_id ... you can then create another table that stores what type of attributes are available.
It it's simplest form, your user and customer would be attached to an *attribute_lookup* or *attribute_link* table by a hasMany (probably) relationship. That attribute_lookup/link table would be connected by a belongsTo/hasOne relationship to the actual Attribute Type and Attribute Value models.
Providing that you normalise your tables correctly, you can stick well within Cake relationship conventions.
You can read more about EAV here.
I have been thinking about this problem for some time now, and I have eventually got around to build a solution for it. What I came up with is a new ORM that can be used on top of CakePHP.
It sort of works as CakePHP 3.0 with entities that represent an id/model, but it is much more advanced and supports multi table inheritance and single table inheritance.
Check it out: https://github.com/erobwen/Cream

Database design: OR relation

I have a database with a "users" table containing data about my users. Each user is to be linked to a company or a college. I wish to have two separate tables "college" and "company" each with a field "ID". So how do I link each record in the users table to either a company or a college?
The basic thing is that I wish to establish an "OR" relationship in the database.
You can use subtype/super-type relationship. Keep all common fields in the organization table. College and company tables contain only fields specific to those entities.
You could use an 'institution' or 'organisation' lookup table, with a structure something like
InstitutionId[PK], InstitutionType, LookupKey
where LookupKey is the PK to either Company or College.
Or,
InstitutionId[PK], CompanyId[FK], CollegeId[FK]
In both cases you link from user to institution, then onto Company and/or College.
I personally prefer the second option, because it allows you to easily validate the FK relationship and also allows (if applicable) for a user to be a member of a company and/or a college.
I would create relationtables. UserCollege and UserCompany. This way you are even able to have users that are linked to both if needed in the future. If not you simply just create a relationrecord on one of the both

Entity Framework naming conventions for many-to-many link tables

We are designing a SQL Server database with link tables for many-to-many relations.
The question is are there any best practices for naming these kinds of tables for use with the entity framework?
Let's say there's a table
Customer
and
Address
Then there is a link table between them, what do we call it?
CustomerAddress ? Or something else?
Thnx
For example, users - UsersInRoles - Roles. If CustomerAddress does not contains anything except CustomerID and AddressID, EF'll generate only two entities Customer (with Addresses property) and Address (with Customers) and there is no any matter how you call this intermediate table

How to design DB table / schema with ease?

Is there a simple method to decide on what fields and indexes are needed for each table in an app you design?
For example, if it is a webapp that simply lets people create lists (any number of lists, and users can create "things to do" list or "shopping" list), and the user can assign other users to edit the list, and whether the list is viewable publicly or to only certain users, how can the tables be design so that it is very accurate and designed quickly? What about the indexes?
I did that in college and then revisited the question some time ago and have a method, but would like to find out if there are standard and good ways to do it out in the field.
Database design is hard ...
As with many things in life, it's a series of tradeoffs. The first thing you need to decide is what DBMS you will use, (MySQL, SQL Server, Oracle, PostgreSQL, one of the "Object-oriented" databases, etc.
Then you need to decide on normalization v. insane numbers of JOINs to get to your data. Questions like "how much logic will I implement in triggers, stored procedures, in app code, etc" need to be addressed.
There is no "Quick'n'Easy" way to design anything but the most trivial of databases.
'Course, that's just my experience. YMWV.
it is beyond the scope of this answer to fully explain database design
I generally break my design into three parts (part 1 and 2 happen up front, while 3 is usually near the project end)
1) create the tables based on relationships (parent/child/etc)
2) create fields based on content (parent has x atributes, etc)
3) create indexes last based on how you select data from your tables
Haven't heard of any formal approaches to this problem but there are rules of thumb. All nouns and business objects become tables, normalized of course. And I'd think the attributes sort of speak for themselves. I guess?
As for indexes, it just comes with working with the data. Any column that's joined off of deserves an index (maybe even clustered). It's very... depends. But there are patterns. But other than optimizing for joins, many indexes are directly related to how the data is used, and this isn't something that can be provided by rule of thumb. Like if you look up users by pk and elsewhere by last_name, last_name deserves an index.
I think the solution is a subjective one. When I have to design tables I look at the Java object that will represent that particular data model and go from there. You'll find a lot of frameworks (Django, CakePHP, RoR) have you develop the model and the frameworks will build the corresponding tables.
So I would suggest evaluating what functionality and data you need to store and develop your tables from that. Also look into whether the tool set you have at your disposal offers to generate the tables for you from the object structure.
I would go for the straightforward (almost) normalized design:
CREATE TABLE lists (
listid serial,
name varchar,
ownerid int references users(userid)
)
CREATE TABLE list_items (
listid int references lists(listid),
value varchar,
date datetime
)
CREATE TABLE permissions (
permissionid serial,
description varchar,
)
CREATE TABLE list_permissions (
listid int references lists(listid),
permissionid int references permissions(permissionid)
userid int references users(userid)
)
CREATE TABLE users (
userid serial,
name varchar
)
Which indexes to create would depend on what are the actual most used queries and how are they performing. For instance, if you query a lot on the lists and list_items (likely) you'd want an index on listid and on name, if you'll be searching by name.
Just some ideas. Hope they're helpful.
I'd try not to lock yourself in if you're still trying to see what works.
Just from your description, you'd want a table for your users' information, as well as:
tbl_lists:
ID_list (primary key)
UserID (foreign key to list owner)
ListName
tbl_listItems:
ID_listItem (primary key)
ListID (foreign key to list)
ItemDescription
tbl_permissions:
ID_permission (primary key)
ListID
UserID (foreign key to user you're granting permission to)
PermissionTypeID (what kind of permission)
tbl_permissionTypes:
ID_permissionType (primary key)
Description ("can view", "can edit", etc.)
The more flexible you can make things while you're designing, the better. You can optimize later.
If you want to keep things very simple and are not too concerned with normalizing. You could create one big table that stores the main object your webapp is based around, ex: lists, and have other smaller supporting tables link to the big table, ex: tbl_listType, tbl_permission, tbl_list_items).
Then when you write queries, you almost certainly include the main table and you can link in other supporting tables for more granular details.

Resources