1

I have a question. How can I delete one field and all other one to many relations?

Field has
 - List<Years>
Years has
- List<Crop>
Crop has
- List<Pesticide>
- List<Fertilizer>

if i use

db.Fields.Remove(field);

it will only delete the field not all related records

How can remove all years if remove a field or if i remove a year all crops will be removed

UPDATE:

I have tried:

 modelBuilder.Entity<Entity.Field>()
             .HasOptional(c => c.Years)
             .WithMany(); 

 Query IQueryable<Entity.Field> query = ctx.Set<Entity.Field>() 
         .Include(c => c.Years); 

 var list = query.ToList();

but I get this error:

Error: MetadataException: The declared type of navigation property FieldManager.Context.Field.Years is not compatible with the result of the specified navigation

derloopkat
  • 6,232
  • 16
  • 38
  • 45
Lyror
  • 924
  • 3
  • 10
  • 19
  • ...what language? – derloopkat May 01 '18 at 09:33
  • Possible duplicate of [How do you ensure Cascade Delete is enabled on a table relationship in EF Code first?](https://stackoverflow.com/questions/5471374/how-do-you-ensure-cascade-delete-is-enabled-on-a-table-relationship-in-ef-code-f) – Stefan May 01 '18 at 09:34
  • c# entity framework 6 – Lyror May 01 '18 at 09:50
  • @Stefan i saw this question but it won't work for me. Here a link to my code: https://hastebin.com/asuwoseriw.scala – Lyror May 01 '18 at 09:54
  • 1
    Hi, I updated your question to reflect your comment. I am missing the essential: `.WillCascadeOnDelete(true);` part. Keep in mind, that if you make your year `Required`, cascade on delete is enabled by default. – Stefan May 01 '18 at 10:01
  • @Stefan i didn't set the Required property. Thanks a lot. Now it works fine. – Lyror May 01 '18 at 13:27

0 Answers0