Entity Framework Update Entity along with child entities (add/update as necessary)

后端 未结 3 1478
一个人的身影
一个人的身影 2021-02-02 15:24

I have a many-to-many relationship between Issues and Scopes in my EF Context. In ASP.NET MVC, I bring up an Edit form that allows the user to edit a

相关标签:
3条回答
  • 2021-02-02 16:16

    Stubs are generally only effective for 1-* relationships. *-* relationships introduce a different set of challenges.

    Namely that when you attach both ends - unlike 1-* - you still have no idea if the relationship already exists or not.

    So that means that this code:

    if (issue.Scopes.Contains(thisScope))
    

    Is probably going to return false every time.

    What I would do is this:

    edmx.Issues.Attach(issue);
    UpdateModel(issue);
    // or ctx.LoadProperty(issue, "Scopes") if it is a POCO class.
    issue.Scopes.Load(); // hit the database to load the current state.
    

    Now you need to find out what you need to add & remove from issue.Scopes. You can do this by comparing based on ID.

    i.e. if you have a set of Scope IDs you want to have related to the issue (relatedScopes)

    Then this code works out what to add and what to remove.

    int[] toAdd = relatedScopes.Except(issue.Scopes.Select(s => s.ID)).ToArray();
    int[] toRemove = issue.Scopes.Select(s => s.ID).Except(relatedScopes).ToArray();
    

    Now for toAdd you do this:

    foreach(int id in toAdd)
    {
       var scope = new Scope{Id = id};
       edmx.Scopes.Attach(scope);
       issue.Scopes.Add(scope);
    }
    

    And for each scope you need to remove

    foreach(int id in toRemove)
    {
       issue.Scopes.Remove(issue.Scopes.Single(s => s.ID == id));
    }
    

    By now the correct relationships should be formed.

    Hope this helps

    Alex

    Microsoft

    0 讨论(0)
  • 2021-02-02 16:25

    Warning, this is just from the top of my head, I didn't try it.

    I don't think you can set a foreign key just like you do with ProjectID.

    you need to retrieve the project and add it to the scope.Project navigation property. EF will take care of the relations when you insert it.

    Now again, I didn't try and might be wrong, but worth a try. Maybe this helps getting you on the way..

    0 讨论(0)
  • 2021-02-02 16:25

    **Disclaimer: I am relatively new to EF, take my answer with a bucket of salt.

    If this is an edit form, I think your issue object should not be a "new" issue, it should pull the issue out of the data store. As far as I can see by doing:

    Issue issue = new Issue { IssueID = id, TSColumn = formIssue.TSColumn }; edmx.Issues.Attach(issue); you are effectively creating a New Issue with the Id of the one you are trying to edit.

    Again, I am here looking for ways to make sense of EF myself. Sometimes I miss my SQL statements.

    0 讨论(0)
提交回复
热议问题