Entity Framework Core - Inserting One-Directional Parent Child Relationship











up vote
2
down vote

favorite












Since Table Per Type isn't available in Core, I had to do a bit of a workaround to get my entities how I like them. Essentially I have a base class with its properties, and a navigation property to its parent:



 public class Provision
{
public Guid ProvisionId { get; set; }
public string ProvisionName { get; set; }
public string ProvisionDescription { get; set; }

public Provision(){}
}

public class CompanyLeaveProvision
{
public Guid ProvisionId { get; set; }
public int CompanyId { get; set; }
public Provision Provision { get; set; }

public CompanyLeaveProvision() { }
}


Configurations:



public void Configure(EntityTypeBuilder<Provision> builder)
{
// Primary Key
builder.HasKey(t => t.ProvisionId);

// Properties
builder.Property(t => t.ProvisionName)
.IsRequired()
.HasMaxLength(40);

builder.Property(t => t.ProvisionDescription)
.HasMaxLength(500);

// Table & Column Mappings
builder.Property(t => t.ProvisionId).HasColumnName("ProvisionID");
builder.Property(t => t.ProvisionName).HasColumnName("ProvisionName");
builder.Property(t => t.ProvisionDescription).HasColumnName("ProvisionDescription");
builder.ToTable("Provision", "Organization");
}

public void Configure(EntityTypeBuilder<CompanyLeaveProvision> builder)
{
// Primary Key
builder.HasKey(t => t.ProvisionId);

// Properties
builder.Property(t => t.ProvisionId)
.IsRequired();

builder.Property(t => t.CompanyId)
.IsRequired();


// Table & Column Mappings
builder.ToTable("CompanyLeaveProvision", "Organization");
builder.Property(t => t.ProvisionId).HasColumnName("ProvisionID");
builder.Property(t => t.CompanyId).HasColumnName("CompanyID");


builder.HasOne(t => t.Provision).WithOne().HasForeignKey<Provision>(t => t.ProvisionId);



}


My context:



ProvisionContext: DbContext, IContext    {
public DbSet<Provision> Provisions { get; set; }
public DbSet<CompanyLeaveProvision> CompanyLeaveProvisions { get; set;}
// OnModelCreating and other code below
}


I have a foreign key constraint on the the Organization.CompanyProvision table that references the ProvisionId property on the Organization.Provision table.



What is happening is the CompanyProvision is being inserted before the base Provision, resulting in this error:




The INSERT statement conflicted with the FOREIGN KEY constraint
"fk_CompanyLeaveProvision_Provision". The conflict occurred in
database "Dev", table "Organization.Provision", column 'ProvisionID'.




To attempt to save, here is the code I am calling:



    _context.Entry(command.Provision.Provision).State = EntityState.Added;
_context.Entry(command.Provision).State = EntityState.Added;
await _context.SaveChangesAsync();


Aside from calling SaveChanges() after each _context.Entry(MyEntity).State = EntityState.Added, is there any way around this issue? I would prefer to have these save at once. I know a stored procedure is also an option, but I would prefer not to do that.



Thank you for your help!










share|improve this question




























    up vote
    2
    down vote

    favorite












    Since Table Per Type isn't available in Core, I had to do a bit of a workaround to get my entities how I like them. Essentially I have a base class with its properties, and a navigation property to its parent:



     public class Provision
    {
    public Guid ProvisionId { get; set; }
    public string ProvisionName { get; set; }
    public string ProvisionDescription { get; set; }

    public Provision(){}
    }

    public class CompanyLeaveProvision
    {
    public Guid ProvisionId { get; set; }
    public int CompanyId { get; set; }
    public Provision Provision { get; set; }

    public CompanyLeaveProvision() { }
    }


    Configurations:



    public void Configure(EntityTypeBuilder<Provision> builder)
    {
    // Primary Key
    builder.HasKey(t => t.ProvisionId);

    // Properties
    builder.Property(t => t.ProvisionName)
    .IsRequired()
    .HasMaxLength(40);

    builder.Property(t => t.ProvisionDescription)
    .HasMaxLength(500);

    // Table & Column Mappings
    builder.Property(t => t.ProvisionId).HasColumnName("ProvisionID");
    builder.Property(t => t.ProvisionName).HasColumnName("ProvisionName");
    builder.Property(t => t.ProvisionDescription).HasColumnName("ProvisionDescription");
    builder.ToTable("Provision", "Organization");
    }

    public void Configure(EntityTypeBuilder<CompanyLeaveProvision> builder)
    {
    // Primary Key
    builder.HasKey(t => t.ProvisionId);

    // Properties
    builder.Property(t => t.ProvisionId)
    .IsRequired();

    builder.Property(t => t.CompanyId)
    .IsRequired();


    // Table & Column Mappings
    builder.ToTable("CompanyLeaveProvision", "Organization");
    builder.Property(t => t.ProvisionId).HasColumnName("ProvisionID");
    builder.Property(t => t.CompanyId).HasColumnName("CompanyID");


    builder.HasOne(t => t.Provision).WithOne().HasForeignKey<Provision>(t => t.ProvisionId);



    }


    My context:



    ProvisionContext: DbContext, IContext    {
    public DbSet<Provision> Provisions { get; set; }
    public DbSet<CompanyLeaveProvision> CompanyLeaveProvisions { get; set;}
    // OnModelCreating and other code below
    }


    I have a foreign key constraint on the the Organization.CompanyProvision table that references the ProvisionId property on the Organization.Provision table.



    What is happening is the CompanyProvision is being inserted before the base Provision, resulting in this error:




    The INSERT statement conflicted with the FOREIGN KEY constraint
    "fk_CompanyLeaveProvision_Provision". The conflict occurred in
    database "Dev", table "Organization.Provision", column 'ProvisionID'.




    To attempt to save, here is the code I am calling:



        _context.Entry(command.Provision.Provision).State = EntityState.Added;
    _context.Entry(command.Provision).State = EntityState.Added;
    await _context.SaveChangesAsync();


    Aside from calling SaveChanges() after each _context.Entry(MyEntity).State = EntityState.Added, is there any way around this issue? I would prefer to have these save at once. I know a stored procedure is also an option, but I would prefer not to do that.



    Thank you for your help!










    share|improve this question


























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      Since Table Per Type isn't available in Core, I had to do a bit of a workaround to get my entities how I like them. Essentially I have a base class with its properties, and a navigation property to its parent:



       public class Provision
      {
      public Guid ProvisionId { get; set; }
      public string ProvisionName { get; set; }
      public string ProvisionDescription { get; set; }

      public Provision(){}
      }

      public class CompanyLeaveProvision
      {
      public Guid ProvisionId { get; set; }
      public int CompanyId { get; set; }
      public Provision Provision { get; set; }

      public CompanyLeaveProvision() { }
      }


      Configurations:



      public void Configure(EntityTypeBuilder<Provision> builder)
      {
      // Primary Key
      builder.HasKey(t => t.ProvisionId);

      // Properties
      builder.Property(t => t.ProvisionName)
      .IsRequired()
      .HasMaxLength(40);

      builder.Property(t => t.ProvisionDescription)
      .HasMaxLength(500);

      // Table & Column Mappings
      builder.Property(t => t.ProvisionId).HasColumnName("ProvisionID");
      builder.Property(t => t.ProvisionName).HasColumnName("ProvisionName");
      builder.Property(t => t.ProvisionDescription).HasColumnName("ProvisionDescription");
      builder.ToTable("Provision", "Organization");
      }

      public void Configure(EntityTypeBuilder<CompanyLeaveProvision> builder)
      {
      // Primary Key
      builder.HasKey(t => t.ProvisionId);

      // Properties
      builder.Property(t => t.ProvisionId)
      .IsRequired();

      builder.Property(t => t.CompanyId)
      .IsRequired();


      // Table & Column Mappings
      builder.ToTable("CompanyLeaveProvision", "Organization");
      builder.Property(t => t.ProvisionId).HasColumnName("ProvisionID");
      builder.Property(t => t.CompanyId).HasColumnName("CompanyID");


      builder.HasOne(t => t.Provision).WithOne().HasForeignKey<Provision>(t => t.ProvisionId);



      }


      My context:



      ProvisionContext: DbContext, IContext    {
      public DbSet<Provision> Provisions { get; set; }
      public DbSet<CompanyLeaveProvision> CompanyLeaveProvisions { get; set;}
      // OnModelCreating and other code below
      }


      I have a foreign key constraint on the the Organization.CompanyProvision table that references the ProvisionId property on the Organization.Provision table.



      What is happening is the CompanyProvision is being inserted before the base Provision, resulting in this error:




      The INSERT statement conflicted with the FOREIGN KEY constraint
      "fk_CompanyLeaveProvision_Provision". The conflict occurred in
      database "Dev", table "Organization.Provision", column 'ProvisionID'.




      To attempt to save, here is the code I am calling:



          _context.Entry(command.Provision.Provision).State = EntityState.Added;
      _context.Entry(command.Provision).State = EntityState.Added;
      await _context.SaveChangesAsync();


      Aside from calling SaveChanges() after each _context.Entry(MyEntity).State = EntityState.Added, is there any way around this issue? I would prefer to have these save at once. I know a stored procedure is also an option, but I would prefer not to do that.



      Thank you for your help!










      share|improve this question















      Since Table Per Type isn't available in Core, I had to do a bit of a workaround to get my entities how I like them. Essentially I have a base class with its properties, and a navigation property to its parent:



       public class Provision
      {
      public Guid ProvisionId { get; set; }
      public string ProvisionName { get; set; }
      public string ProvisionDescription { get; set; }

      public Provision(){}
      }

      public class CompanyLeaveProvision
      {
      public Guid ProvisionId { get; set; }
      public int CompanyId { get; set; }
      public Provision Provision { get; set; }

      public CompanyLeaveProvision() { }
      }


      Configurations:



      public void Configure(EntityTypeBuilder<Provision> builder)
      {
      // Primary Key
      builder.HasKey(t => t.ProvisionId);

      // Properties
      builder.Property(t => t.ProvisionName)
      .IsRequired()
      .HasMaxLength(40);

      builder.Property(t => t.ProvisionDescription)
      .HasMaxLength(500);

      // Table & Column Mappings
      builder.Property(t => t.ProvisionId).HasColumnName("ProvisionID");
      builder.Property(t => t.ProvisionName).HasColumnName("ProvisionName");
      builder.Property(t => t.ProvisionDescription).HasColumnName("ProvisionDescription");
      builder.ToTable("Provision", "Organization");
      }

      public void Configure(EntityTypeBuilder<CompanyLeaveProvision> builder)
      {
      // Primary Key
      builder.HasKey(t => t.ProvisionId);

      // Properties
      builder.Property(t => t.ProvisionId)
      .IsRequired();

      builder.Property(t => t.CompanyId)
      .IsRequired();


      // Table & Column Mappings
      builder.ToTable("CompanyLeaveProvision", "Organization");
      builder.Property(t => t.ProvisionId).HasColumnName("ProvisionID");
      builder.Property(t => t.CompanyId).HasColumnName("CompanyID");


      builder.HasOne(t => t.Provision).WithOne().HasForeignKey<Provision>(t => t.ProvisionId);



      }


      My context:



      ProvisionContext: DbContext, IContext    {
      public DbSet<Provision> Provisions { get; set; }
      public DbSet<CompanyLeaveProvision> CompanyLeaveProvisions { get; set;}
      // OnModelCreating and other code below
      }


      I have a foreign key constraint on the the Organization.CompanyProvision table that references the ProvisionId property on the Organization.Provision table.



      What is happening is the CompanyProvision is being inserted before the base Provision, resulting in this error:




      The INSERT statement conflicted with the FOREIGN KEY constraint
      "fk_CompanyLeaveProvision_Provision". The conflict occurred in
      database "Dev", table "Organization.Provision", column 'ProvisionID'.




      To attempt to save, here is the code I am calling:



          _context.Entry(command.Provision.Provision).State = EntityState.Added;
      _context.Entry(command.Provision).State = EntityState.Added;
      await _context.SaveChangesAsync();


      Aside from calling SaveChanges() after each _context.Entry(MyEntity).State = EntityState.Added, is there any way around this issue? I would prefer to have these save at once. I know a stored procedure is also an option, but I would prefer not to do that.



      Thank you for your help!







      c# entity-framework-core






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 7 at 19:55









      Nashmár

      1831115




      1831115










      asked Nov 7 at 19:07









      billatron

      259




      259
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          It's because this fluent mapping



          .HasForeignKey<Provision>(t => t.ProvisionId)


          is telling EF Core that Provision is the dependent entity and has FK to the principal entity CompanyLeaveProvision, while the database model is the opposite.



          So simply change Provision to CompanyLeaveProvision



          .HasForeignKey<CompanyLeaveProvision>(t => t.ProvisionId)





          share|improve this answer





















          • That works perfectly, thank you so much!
            – billatron
            Nov 7 at 19:49











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53196167%2fentity-framework-core-inserting-one-directional-parent-child-relationship%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote



          accepted










          It's because this fluent mapping



          .HasForeignKey<Provision>(t => t.ProvisionId)


          is telling EF Core that Provision is the dependent entity and has FK to the principal entity CompanyLeaveProvision, while the database model is the opposite.



          So simply change Provision to CompanyLeaveProvision



          .HasForeignKey<CompanyLeaveProvision>(t => t.ProvisionId)





          share|improve this answer





















          • That works perfectly, thank you so much!
            – billatron
            Nov 7 at 19:49















          up vote
          1
          down vote



          accepted










          It's because this fluent mapping



          .HasForeignKey<Provision>(t => t.ProvisionId)


          is telling EF Core that Provision is the dependent entity and has FK to the principal entity CompanyLeaveProvision, while the database model is the opposite.



          So simply change Provision to CompanyLeaveProvision



          .HasForeignKey<CompanyLeaveProvision>(t => t.ProvisionId)





          share|improve this answer





















          • That works perfectly, thank you so much!
            – billatron
            Nov 7 at 19:49













          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          It's because this fluent mapping



          .HasForeignKey<Provision>(t => t.ProvisionId)


          is telling EF Core that Provision is the dependent entity and has FK to the principal entity CompanyLeaveProvision, while the database model is the opposite.



          So simply change Provision to CompanyLeaveProvision



          .HasForeignKey<CompanyLeaveProvision>(t => t.ProvisionId)





          share|improve this answer












          It's because this fluent mapping



          .HasForeignKey<Provision>(t => t.ProvisionId)


          is telling EF Core that Provision is the dependent entity and has FK to the principal entity CompanyLeaveProvision, while the database model is the opposite.



          So simply change Provision to CompanyLeaveProvision



          .HasForeignKey<CompanyLeaveProvision>(t => t.ProvisionId)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 7 at 19:16









          Ivan Stoev

          96.4k765119




          96.4k765119












          • That works perfectly, thank you so much!
            – billatron
            Nov 7 at 19:49


















          • That works perfectly, thank you so much!
            – billatron
            Nov 7 at 19:49
















          That works perfectly, thank you so much!
          – billatron
          Nov 7 at 19:49




          That works perfectly, thank you so much!
          – billatron
          Nov 7 at 19:49


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53196167%2fentity-framework-core-inserting-one-directional-parent-child-relationship%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          Tangent Lines Diagram Along Smooth Curve

          Yusuf al-Mu'taman ibn Hud

          Zucchini