1

I encountered some different behaviour between EF6 and EF Core and would like to know if I could get the same behaviour in EF Core like in EF6, e.g. by changing some configuration.

public partial class Parent
{
  public int Id { get; set; }
  public virtual ICollection<Child> Childs { get; set; }
}

public partial class Child
{
  public int Id { get; set; }
  public int ParentId { get; set; }
  public string SomeProperty { get; set; }
  public virtual Parent Parent { get; set; }
}

public class MyContext : DbContext
{
  public virtual DbSet<Parent> Parents { get; set; }
  public virtual DbSet<Child> Childs { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<Child>()
    .HasOne(c => c.Parent)
    .WithMany(p => p.Childs)
    .HasForeignKey(c => c.ParentId);

  modelBuilder.Entity<Parent>()
    .HasMany(p => p.Childs)
    .WithOne(c => c.Parent);
}

The following code saves a new Child using EF6 but not using EF Core

var db = new MyContext();
var parent = db.Parents.First();

var child = new Child
{
  SomeProperty = "foobar",
  Parent = parent
}
db.SaveChanges();

What also works in EF Core is when I add the following, of course.

db.Childs.Add(child);

Edit: For the EF6 model ObjectContext and classes generated by EDMX have been used.

ppickel
  • 21
  • 4

0 Answers0