2

I have a problem in my project. In one database relations have a join to self with many to many.

What any of people solve this problem in Entity FrameWork?

tereško
  • 58,060
  • 25
  • 98
  • 150

2 Answers2

3

Any many-to-many relationship should create a new table to represent the pairings.

Example: say you have a table People, and you want to show who gave birthday gifts. A person can give gifts to many friends, and a person may receive gifts from many other people.

CREATE TABLE People (person_id INT PRIMARY KEY);

CREATE TABLE GiftGiving (
  from_person_id INT,
  to_person_id INT,
  PRIMARY KEY (from_person_id, to_person_id),
  FOREIGN KEY (from_person_id) REFERENCES People(person_id),
  FOREIGN KEY (to_person_id)   REFERENCES People(person_id)
);

Re your comment:

For EF implementations, see these related questions:

Community
  • 1
  • 1
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
  • Hi Bill. New to SQL here. Is it the commonly held recommended style to Uppercase Table Names? Is there a style guide you would recommend? Also I noticed, in a sense you put the `from_person_id` twice as `from_person_id INT` and `FOREIGN KEY (from_person_id) REFERENCES People(person_id),` why is that? Could you have just had the `FOREIGN KEY (from_person_id) REFERENCES People(person_id),`? Would there be down sides to that? – ScottyBlades May 17 '21 at 06:48
  • 1
    The column definition and the foreign key are separate. You can't make a foreign key constraint unless you first define the column. For example, there is no place in a foreign key constraint to define the column's data type or other column options. Some databases support a shorthand , but MySQL does not support it (see https://stackoverflow.com/questions/63727924/major-bug-in-mysql-8-x-foreign-keys/63728082#63728082). – Bill Karwin May 17 '21 at 14:30
  • As for style guide, there's no universal style guide for SQL. What is more important is that you choose what works for you in a given project, then you follow it consistently in your project. This is the same guidance as for most programming languages. – Bill Karwin May 17 '21 at 14:34
1

I simply put an ICollection to itself. Let EF handle the db layer. public class Person{ public virtual ICollection OtherPersons {get;set;} }

Péter
  • 2,161
  • 3
  • 21
  • 30