{"id":679,"date":"2023-10-23T09:00:57","date_gmt":"2023-10-23T15:00:57","guid":{"rendered":"https:\/\/kop.lat\/blog\/?p=679"},"modified":"2023-10-23T09:00:57","modified_gmt":"2023-10-23T15:00:57","slug":"multiple-relations-dbcontext-ef-core","status":"publish","type":"post","link":"https:\/\/kop.lat\/blog\/multiple-relations-dbcontext-ef-core\/","title":{"rendered":"Multiple relations dbContext (EF Core)"},"content":{"rendered":"\n<p><\/p>\n\n\n\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#5E69FF\"><div class=\"control-language\"><div class=\"dm-buttons\"><div class=\"dm-buttons-left\"><div class=\"dm-button-snippet red-button\"><\/div><div class=\"dm-button-snippet orange-button\"><\/div><div class=\"dm-button-snippet green-button\"><\/div><\/div><div class=\"dm-buttons-right\"><a id=\"dm-copy-raw-code\"><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\" style=\"display:none\">Copied<\/span><span class=\"dm-error-message\" style=\"display:none\">Use a different Browser<\/span><\/a><\/div><\/div><pre class=\" line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-clike\">using System;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.ComponentModel.DataAnnotations.Schema;\nusing System.Linq;\nusing Microsoft.Data.SqlClient;\nusing Microsoft.EntityFrameworkCore;\n\npublic class Program\n{\n    public static string ConnectionString = FiddleHelper.GetConnectionStringSqlServer();\n\n    public static void Main()\n    {\n        using (var context = new MyDbContext())\n        {\n            \/\/ ensure database creation here\n            context.Database.EnsureCreated();\n\n            \/\/ Seed data here\n            SeedData(context);\n\n            \/\/ Query data, just creating a sample, instantiating the parent model\n            var results = context.ParentModels\n                .Include(p => p.ChildModel1)\n                .Include(p => p.ChildModel2s)\n                .Include(p => p.ChildModel3s)\n                .ToList();\n\n            \/\/ Displaying results here\n            FiddleHelper.WriteTable(results);\n        }\n    }\n\n    \/\/ This is the DbContext\n    public class MyDbContext : DbContext\n    {\n        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)\n        {\n            optionsBuilder.UseSqlServer(ConnectionString);\n        }\n\n        protected override void OnModelCreating(ModelBuilder modelBuilder)\n        {\n            modelBuilder.Entity&lt;ParentModel>()\n                .HasOne(p => p.ChildModel1)\n                .WithOne(c => c.ParentModel)\n                .HasForeignKey&lt;ChildModel1>(c => c.ParentModelId);\n\n            modelBuilder.Entity&lt;ParentModel>()\n                .HasMany(p => p.ChildModel2s)\n                .WithOne(c => c.ParentModel)\n                .HasForeignKey(c => c.ParentModelId);\n\n            modelBuilder.Entity&lt;ParentModel>()\n                .HasMany(p => p.ChildModel3s)\n                .WithMany(c => c.ParentModels)\n                .UsingEntity&lt;Dictionary&lt;string, object>>(\n                    \"ParentModelChildModel3\",\n                    j => j\n                        .HasOne&lt;ChildModel3>()\n                        .WithMany()\n                        .HasForeignKey(\"ChildModel3Id\")\n                        .HasConstraintName(\"FK_ParentModelChildModel3_ChildModel3_ChildModel3Id\")\n                        .OnDelete(DeleteBehavior.Cascade),\n                    j => j\n                        .HasOne&lt;ParentModel>()\n                        .WithMany()\n                        .HasForeignKey(\"ParentModelId\")\n                        .HasConstraintName(\"FK_ParentModelChildModel3_ParentModel_ParentModelId\")\n                        .OnDelete(DeleteBehavior.Cascade),\n                    j =>\n                    {\n                        j.HasKey(\"ParentModelId\", \"ChildModel3Id\");\n                        j.HasIndex(\"ChildModel3Id\").HasName(\"IX_ParentModelChildModel3_ChildModel3Id\");\n                    });\n        }\n\n        public DbSet&lt;ParentModel> ParentModels { get; set; }\n        public DbSet&lt;ChildModel1> ChildModel1s { get; set; }\n        public DbSet&lt;ChildModel2> ChildModel2s { get; set; }\n        public DbSet&lt;ChildModel3> ChildModel3s { get; set; }\n    }\n\n    \/\/ ParentModel here\n    public class ParentModel\n    {\n        [Key]\n        public int Id { get; set; }\n\n        public string Name { get; set; }\n\n        public ChildModel1 ChildModel1 { get; set; }\n\n        public List&lt;ChildModel2> ChildModel2s { get; set; }\n\n        public List&lt;ChildModel3> ChildModel3s { get; set; }\n    }\n\n\/\/ ChildModel1\n    public class ChildModel1\n    {\n        [Key]\n        public int Id { get; set; }\n\n        public string Name { get; set; }\n\n        public int ParentModelId { get; set; }\n        public ParentModel ParentModel { get; set; }\n    }\n\n\/\/ ChildModel2\n    public class ChildModel2\n    {\n        [Key]\n        public int Id { get; set; }\n\n        public string Name { get; set; }\n\n        public int ParentModelId { get; set; }\n        public ParentModel ParentModel { get; set; }\n    }\n\n\/\/ ChildModel3\n    {\n        [Key]\n        public int Id { get; set; }\n\n        public string Name { get; set; }\n\n        public List&lt;ParentModel> ParentModels { get; set; }\n    }\n\n    \/\/ Seeding the data here\n    public static void SeedData(MyDbContext context)\n    {\n        var parentModel = new ParentModel { Name = \"Parent Model\" };\n        var childModel1 = new ChildModel1 { Name = \"Child Model 1\", ParentModel = parentModel };\n        var childModel2_1 = new ChildModel2 { Name = \"Child Model 2-1\", ParentModel = parentModel };\n        var childModel2_2 = new ChildModel2 { Name = \"Child Model 2-2\", ParentModel = parentModel };\n        var childModel3_1 = new ChildModel3 { Name = \"Child Model 3-1\" };\n        var childModel3_2 = new ChildModel3 { Name = \"Child Model 3-2\" };\n\n        parentModel.ChildModel1 = childModel1;\n        parentModel.ChildModel2s = new List&lt;ChildModel2> { childModel2_1, childModel2_2 };\n        parentModel.ChildModel3s = new List&lt;ChildModel3> { childModel3_1, childModel3_2 };\n\n        context.ParentModels.Add(parentModel);\n        context.ChildModel1s.Add(childModel1);\n        context.ChildModel2s.AddRange(childModel2_1, childModel2_2);\n        context.ChildModel3s.AddRange(childModel3_1, childModel3_2);\n\n        context.SaveChanges();\n    }\n}\n<\/code><\/pre><\/div><\/div>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":258,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[39,41,51,32,88,52,7,40,111],"tags":[],"_links":{"self":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/679"}],"collection":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/comments?post=679"}],"version-history":[{"count":1,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/679\/revisions"}],"predecessor-version":[{"id":680,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/679\/revisions\/680"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/media\/258"}],"wp:attachment":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/media?parent=679"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/categories?post=679"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/tags?post=679"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}