views:

37

answers:

1

This is a fairly simple question (or at least from the outset it should be).

I am looking into efficient ways to model a One to Many relationship where the many is the same type.

Example

Say we have a Person Entity, and this person has 0 to many Sub-Persons, and the Sub-Persons have 0 or 1 Parent-Person.

The answer should take into consideration read optimization & querying simplicity from Linq to Entity Framework. Answers relating to underlying Database table structure for best read performance are also very welcome (as long as they can be mapped to by EF4).

+1  A: 

This looks like a case of self-referential foreign key. (oracle)

A generally used example is the Employee-Manager relationship. A given employee can be a manager (to other employees) and can in-turn have a manager (or not, if he is the boss).

The table definition and constraint definition would be like this.

CREATE TABLE EMP
(
  EMPNO     NUMBER(4)                           NOT NULL,
  ENAME     VARCHAR2(10 BYTE),
  JOB       VARCHAR2(9 BYTE),
  MGR       NUMBER(4),
  HIREDATE  DATE,
  SAL       NUMBER(7,2),
  COMM      NUMBER(7,2),
  DEPTNO    NUMBER(2)
)

and the constraint would be ..

alter table emp add constraint fk_emp_mgr
foreign key mgr references emp(empno);

This indicates that the manager Id for a given employee must himself be an employee. Here is the sample data.

EMPNO ENAME JOB MGR

7369 SMITH CLERK 7902
7499 ALLEN SALESMAN 7698
7521 WARD SALESMAN 7698
7566 JONES MANAGER 7839
7654 MARTIN SALESMAN 7698
7698 BLAKE MANAGER 7839
7782 CLARK MANAGER 7839
7788 SCOTT ANALYST 7566
7839 KING PRESIDENT 
7844 TURNER SALESMAN 7698
7876 ADAMS CLERK 7788
7900 JAMES CLERK 7698
7902 FORD ANALYST 7566
7934 MILLER CLERK 7782

As you can see, all employees have a manager (except KING who is the company's boss.). each of them is in turn an employee.

Note that this is a model that is suitable and perfect for OLTP style systems. There is no redundant data and data integrity constraints are taken care of.

Rajesh