简体   繁体   中英

EF Core not delete related entity

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()
    {

    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM