I
I
Igor2018-06-27 12:21:27
C++ / C#
Igor, 2018-06-27 12:21:27

Entity Framework: How to save an object with a large nesting of detached objects?

Good day.
At the front, an object of this kind is collected from data / edited:

{
  "author": {
    "id": 119,
    "displayName": "System"
  },
  "modify": {
    "id": 119,
    "displayName": "System"
  },
  "chapters": {
    "chapterList": [{
      "author": {
        "id": 119,
        "displayName": "System"
      },
      "modify": {
        "id": 119,
        "displayName": "System"
      },
      "id": 99,
      "creationDate": "2018-06-27T10:50:27.75+03:00",
      "modifyDate": "2018-06-27T10:50:27.75+03:00",
      "title": "chapter 3"
        },
        {
      "author": {
        "id": 119,
        "displayName": "System"
      },
      "modify": {
        "id": 119,
        "displayName": "System"
      },
      "id": 97,
      "creationDate": "2018-06-27T10:50:27.75+03:00",
      "modifyDate": "2018-06-27T10:50:27.75+03:00",
      "title": "Chapter 1"
    }],
    "Id": 37
  },
  "id": 58,
  "createDate": "2018-06-27T10:50:27.79+03:00",
  "modifyDate": "2018-06-27T11:03:07.55+03:00",
  "title": "Project 1"
}

On the back at
public void Endpoint(Project project){
dbContext.Projects.Attach(project);
dbContext.SaveChanges();
}

at the attack stage, an expression about duplication of primary keys flies out, when trying to attach to the data context from the author/modify fields, nested entities, which is quite logical, because often they intersect.
Actually the question is how to be?
So far, I see the following scenario:
Before attacking the root entity, run through all levels of the hierarchy and replace data with data from the context, getting it from on the fly, and replacing field/property values ​​with values ​​from the resulting entity. But in this decision, I'm confused about how this ton of code + a car of queries to the database will affect performance.
Or is there a more elegant solution that I just don't see?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny, 2018-06-27
Maltsev @maltsever

Hey! And what about getting an entity with all the necessary Includes (we still need them for comparison), go over nested entities and sheets, delete unnecessary ones, add new ones, and so on. And then save. Or is there some underlying reason?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question