0

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() { } } 
2
  • Is there actualy a record with id == 2 in the dataset? Commented Oct 19, 2017 at 8:18
  • Yes of course. This is a EF log: SET NOCOUNT ON; DELETE FROM [cat].[h_tree] WHERE [id] = @p0; SELECT @@ROWCOUNT; Commented Oct 19, 2017 at 8:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

8 Comments

I tried this syntax: modelBuilder.Entity<Tree>().HasOne(x => x.Translation).WithOne().OnDelete(DeleteBehavior.Cascade); but it doesn't work.
I have following error: The child/dependent side could not be determined for the one-to-one relationship that was detected between 'Tree.Translation' and 'Translation'. To identify the child/dependent side of the relationship, configure the foreign key property.
@bielu000 So what is your foreign key field in Translationand why didn't you put it in your .WithOne method?
What I need put into WithOne method? This syntaxt is not correct: modelBuilder.Entity<Tree>().HasOne(x => x.Translation).WithOne(x => x.Id) I have an error: " modelBuilder.Entity<Tree>().HasOne(x => x.Translation).WithOne(x => x.Id)"
@bielu000 I have no idea because I don't know what your Translation class looks like. What is your foreign key there?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.