EF Core not delete related entity

c# entity-framework entity-framework-core

Question

I try to remove my entity with it related entity, but Entity Framework doen't want to do this.

Here is the code:

        var tr = _context.Trees
            .Include(x => x.Translation)
            .FirstOrDefault(x => x.Id == 2);

        _context.Remove(tr);
        _context.SaveChanges();

Context:

  modelBuilder.Entity<Tree>().ToTable("h_tree");
  modelBuilder.Entity<Tree>().HasOne(x => x.Translation);

Tree class:

public class Tree 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Translation Translation { get; set; }
}

Anyone have idea why related entity can't be removed?

Translation class:

public class Translation 
{
    public long Id { get; set; }
    public string Pl { get; set; }
    public string En { get; set; }
    public string De { get; set; }
    public string Cz { get; set; }
    public string It { get; set; }
    public string Ru { get; set; }
    public string Fr { get; set; }

    public Translation()
    {

    }
}
1
0
10/19/2017 8:27:41 AM

Popular Answer

You seem to have missed to say whether this is a one-to-one or one-to-many relationship.

.HasOne() needs to be paired with a .With*() method. Either .WithOne() or .WithMany().


It seems your Translation class is missing a Foreign key.

Add a property called TreeId and use that in your .WithOne() call.

1
10/19/2017 8:45:18 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