Share via

EF Core correct model design

Krzysiek P 1 Reputation point
2021-08-23T05:19:55.17+00:00

I'm trying to set the model as below,

     public class Person
        {
            [Key]
            public int PersonId { get; set; }
            public string Name { get; set; }

            public List<Person> Friends { get; set; }
            public List<Person> Enemies { get; set; }
        }

But by default, ef core does not create such relations as I would like,

Default ef core create two tables:

CREATE TABLE `persons` (
  `PersonId` int(11) NOT NULL AUTO_INCREMENT,
  `Name` longtext,
  PRIMARY KEY (`PersonId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

and

CREATE TABLE `personperson` (
  `EnemesPersonId` int(11) NOT NULL,
  `FriendsPersonId` int(11) NOT NULL,
  PRIMARY KEY (`EnemesPersonId`,`FriendsPersonId`),
  KEY `IX_PersonPerson_FriendsPersonId` (`FriendsPersonId`),
  CONSTRAINT `FK_PersonPerson_Persons_EnemesPersonId` FOREIGN KEY (`EnemesPersonId`) REFERENCES `persons` (`PersonId`) ON DELETE CASCADE,
  CONSTRAINT `FK_PersonPerson_Persons_FriendsPersonId` FOREIGN KEY (`FriendsPersonId`) REFERENCES `persons` (`PersonId`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

I would expect three tables

How can I solve this problem

Developer technologies | .NET | Entity Framework Core

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.