Reputation: 2241
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()
{
}
}
Upvotes: 0
Views: 1174
Reputation: 77285
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.
Upvotes: 1