Entity Framework will not SaveChanges for new two-tier entity

I am building an ASP.NET MVC site using the ADO.NET Entity Framework. I have an entity model that includes these entities associated with foreign keys:

Report (ID, Date, Title, Report_Type_ID, etc.)

  • SubReport (ID, ReportText, etc.) is a one-to-one relationship with Report.
    • ReportSource (ID, Name, Description) - one-to-many relationship with Sub_Report.
      • ReportSourceType (ID, name, description) - one-to-many relationship with ReportSource.
      • Contact (identifier, name, address, etc.) is a one-to-one relationship with Report_Source.

For each type of SubReport, there is a Create.aspx page. The post post method returns a new Sub_Report object.

Before that, in my post method, I followed this process:

  • Set the properties for the new report object from the page fields.
  • Set the entity properties specific to SubReport from the page fields.
  • Define the report of the SubReport object to the new Report object created in 1.
  • Given the identifier provided by the page, find the ReportSource and set the ReportSource object of the Sub_Report object for the found object.
  • SaveChanges.

This workflow went well just a couple of weeks. Then last week something changed and it no longer works. Now, instead of the save operation, I get this exception:

UpdateException: "Entities in 'DIR2_5Entities.ReportSourceSet' 
participate in the 'FK_ReportSources_ReportSourceTypes' relationship. 
0 related 'ReportSourceTypes' were found. 1 'Report_Source_Types' is expected."

:

  • SubReport ReportSource , .
  • Report_Source ReportSourceType.

SQL Profiler SQL . - , ?

: SubReport . Report , , . SubReports - , . SubReport , , SubReport .

+3
6

, 1 - 1 . reportourceset , reportorttype , . , .

0

, , , 3 , . , - , - .

:

  • SaveChanges() . . , , , . Report_Source_Type.
  • , , , . , , , .

context.GetObjectByKey, , context.Attach, .

+6

, , FK, PK.

PK .

+2

, ReportSource NoTracking EntityState == 'Detached'. , , .

+1

- , " " "". .

0

, , .

:

Pet pet = new Pet();
context.Pets.Add(pet);
// forgot this: petOwner.Pets.Add(pet);
0
source

Source: https://habr.com/ru/post/1715361/


All Articles