EfCore 3 and Owned Type in same table, How do you set owned instance

entity-framework-core

Question

How do you set owned type instance with efcore3?

In following example an exception is raised

'The entity of type 'Owned' is sharing the table 'Principals' with entities of type 'Principal', but there is no entity of this type with the same key value that has been marked as 'Added'.

If I set Child property inline savechanges doesn't update child properties

I can't find any example about this. I tried with several efcore3 builds and daily builds. What didn't I understand?

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;

namespace TestEF
{
  class Program
  {
    static void Main(string[] args)
    {
      var id = Guid.NewGuid();

      using (var db = new Ctx())
      {
        db.Database.EnsureDeleted();
        db.Database.EnsureCreated();

        var p = new Principal {Id = id};
        db.Principals.Add(p);
        db.SaveChanges();
      }

      using (var db = new Ctx())
      {
        var p = db.Principals.Single(o => o.Id == id);
        p.Child = new Owned();
        p.Child.Prop1 = "Test2";
        p.Child.Prop2 = "Test2";
        db.SaveChanges();
      }
    }

    public class Principal
    {
      public Guid Id { get; set; }
      public Owned Child { get; set; }
    }

    public class Owned
    {
      public string Prop1 { get; set; }
      public string Prop2 { get; set; }
    }

    public class Ctx : DbContext
    {
      public DbSet<Principal> Principals { get; set; }

      protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
      {
        optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=TestEF;Trusted_Connection=True;Persist Security Info=true");
      }

      protected override void OnModelCreating(ModelBuilder mb)
      {
        var emb = mb.Entity<Principal>();
        emb
          .OwnsOne(o => o.Child, cfg =>
          {
            cfg.Property(o => o.Prop1).HasMaxLength(30);
            //cfg.WithOwner();
          });
      }
    }
  }
}
1
0
8/30/2019 8:52:08 PM

Accepted Answer

This is a bug, filed at https://github.com/aspnet/EntityFrameworkCore/issues/17422

As a workaround you could make the child appear as modified:

db.ChangeTracker.DetectChanges();
var childEntry = db.Entry(p.Child);
childEntry.State = EntityState.Modified;
db.SaveChanges();
1
8/26/2019 4:44:20 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow