{"id":23763882,"url":"https://github.com/tomashubelbauer/ef-relationship","last_synced_at":"2025-06-16T06:07:17.342Z","repository":{"id":107986076,"uuid":"170712725","full_name":"TomasHubelbauer/ef-relationship","owner":"TomasHubelbauer","description":"Exploration into the EF conventions about principal-dependent navigation properties","archived":false,"fork":false,"pushed_at":"2022-04-14T20:12:36.000Z","size":3,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-06-01T16:42:39.518Z","etag":null,"topics":["ef","ef-core","entity-framework","entity-framework-core","orm"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/TomasHubelbauer.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2019-02-14T15:24:22.000Z","updated_at":"2024-10-04T21:20:19.000Z","dependencies_parsed_at":null,"dependency_job_id":"cf7eb2ac-a424-43ae-84f3-4608f0949700","html_url":"https://github.com/TomasHubelbauer/ef-relationship","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/TomasHubelbauer/ef-relationship","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TomasHubelbauer%2Fef-relationship","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TomasHubelbauer%2Fef-relationship/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TomasHubelbauer%2Fef-relationship/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TomasHubelbauer%2Fef-relationship/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/TomasHubelbauer","download_url":"https://codeload.github.com/TomasHubelbauer/ef-relationship/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TomasHubelbauer%2Fef-relationship/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":260109486,"owners_count":22960031,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ef","ef-core","entity-framework","entity-framework-core","orm"],"created_at":"2024-12-31T22:13:46.353Z","updated_at":"2025-06-16T06:07:17.330Z","avatar_url":"https://github.com/TomasHubelbauer.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# EF Core Principal\u003c-\u003eDependant IDs\r\n\r\nThis repository explores how EF Core handles principal-dependent relationships\r\nand the navigation properties related to those by convention.\r\n\r\nWe're going to demonstrate a 1:1 association between two entities and observe\r\nEF Core manage the IDs of both ends for us. Then we are going to change them and\r\nwatch the IDs stay in sync. Next we are going to try to forcefully set incorrect\r\nIDs and will observe EF Core push back on that idea.\r\n\r\n- [ ] Do the above\r\n\r\nLet's create a new .NET Core application and install the EF Core package to it,\r\nincluding the SQL Server provider support, because we are going to be using\r\nLocalDB.\r\n\r\nNote that I am installing the NuGet packages from the official NuGet source and\r\nin order to obtain consistent results, you should disable other package sources\r\nin your Visual Studio \u003e Tools \u003e Options \u003e NuGet Package Manager \u003e Package\r\nSources option. It is enough to uncheck them while installing the packages\r\nbelow.\r\n\r\n```powershell\r\ndotnet new console\r\ndotnet add package Microsoft.EntityFrameworkCore\r\ndotnet add package Microsoft.EntityFrameworkCore.SqlServer\r\n```\r\n\r\nNow that we have the application set up, we also need to set up the LocalDB\r\ndatabase. We're going to call it by the name of the application namespace, which\r\nworks out to be `ef_core_principal_dependent_ids` since the repository directory\r\nname where we've run `dotnet new` is called `ef-core-principal-dependent-ids`.\r\nBy doing this we can use `nameof` in the source code in the connection string.\r\n\r\n```powershell\r\nsqllocaldb create ef_core_principal_dependent_ids -s\r\n```\r\n\r\nNote that the `-s` switch automatically starts the instance after creation.\r\n\r\nWe are not going to be adding a dependency on\r\n`Microsoft.EntityFrameworkCore.Design` as we do not need the `dotnet ef` tool,\r\nwe are not going to use EF Core Migrations.\r\n\r\nLet's check everything compiles: `dotnet run`.\r\n\r\nNow that we have the application up and running, we can move on to the entity\r\nclasses and the application database context setup.\r\n\r\n```csharp\r\npublic class User\r\n{\r\n    public int Id { get; set; }\r\n    public string Name { get; set; }\r\n    public int CarId { get; set; }\r\n    public Car Car { get; set; }\r\n}\r\n\r\npublic class Car\r\n{\r\n    public int Id { get; set; }\r\n    public string Make { get; set; }\r\n    public string Model { get; set; }\r\n    public int UserId { get; set; }\r\n    public User User { get; set; }\r\n}\r\n```\r\n\r\nThe model looks good, now for the application database context class and the\r\ndatabase connection:\r\n\r\n```csharp\r\npublic class AppDbContext: DbContext\r\n{\r\n    public DbSet\u003cUser\u003e Users { get; set; }\r\n    public DbSet\u003cCar\u003e Cars { get; set; }\r\n    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)\r\n    {\r\n        optionsBuilder.UseSqlServer($@\"Server=(localdb)\\{nameof(ef_core_principal_dependent_ids)};Database={nameof(ef_core_principal_dependent_ids)};\");\r\n    }\r\n}\r\n```\r\n\r\nTo test this out, we will connect to the database and reset it by dropping it\r\nand recreating it. This will help with repeatability of this demo.\r\n\r\n```csharp\r\nstatic void Main(string[] args)\r\n{\r\n    using (var appDbContext = new AppDbContext())\r\n    {\r\n        appDbContext.Database.EnsureDeleted();\r\n        appDbContext.Database.EnsureCreated();\r\n        Console.WriteLine(\"The database has been reset.\");\r\n    }\r\n}\r\n```\r\n\r\nRunning this (after adding `Microsoft.EntityFrameworkCore` namespace import),\r\nwe encounter this issue:\r\n\r\n**The child/dependent side could not be determined for the one-to-one relationship between 'Car.User' and 'User.Car'.**\r\n\r\nThis makes sense, EF Core has no way of knowing which side of the 1:1\r\nrelationship is the principal and which one is the dependant.\r\n\r\nLet's help it understand using the fluent API.\r\n\r\n```csharp\r\nprotected override void OnModelCreating(ModelBuilder modelBuilder)\r\n{\r\n    modelBuilder\r\n        .Entity\u003cUser\u003e()\r\n        .HasOne(principal =\u003e principal.Car)\r\n        .WithOne(dependant =\u003e dependant.User)\r\n        .HasForeignKey\u003cCar\u003e(car =\u003e car.UserId);\r\n}\r\n```\r\n\r\nNow for the first scenarion - us adding a user and a car, and EF assigning the\r\ncorrect IDs:\r\n\r\nWhoops! It doesn't. I asked https://github.com/aspnet/EntityFrameworkCore/issues/14704.\r\n\r\nI seem to have been mistaken remembering this working.\r\n\r\n## To-Do\r\n\r\n### Fix the misspelling of \"dependant\" in the repo name and the source code\r\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftomashubelbauer%2Fef-relationship","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftomashubelbauer%2Fef-relationship","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftomashubelbauer%2Fef-relationship/lists"}