Skip to content

Unable to insert an entity with one or more many-to-many relations without inserting the relations itself #69

Description

@FlorianWolters

Hi,

I do want to insert a new entity with already existing relations into a database (I am using Entity Framework 5).

The new entity itself should be added to the database, but the relation entities should not be added (only the relationship should be created).

The source code of the Create method of my Controller class:

[HttpPost]
[ValidateAntiForgeryToken]
public override ActionResult Create(MetadataViewModel viewModel)
{
    if (this.ModelState.IsValid)
    {
        Metadata model = viewModel.Model;
        model.TechnicalWriters = new List<Person>();

        foreach (var id in viewModel.SelectedTechnicalWriterIdentityValues)
        {
            model.TechnicalWriters.Add(new Person { Id = id });
            // model.TechnicalWriters.Add(this.personRepository.Get(id));
        }

        this.Repository.Add(model);

        return this.RedirectToIndexAction();
    }

    return View(this.CreateViewModel(viewModel.Model));
}

The call to this.Repository.Add throws an exception with the following message:

"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."

I also tried to Eager Load the referenced entities via another repository (see commented line above), but that raises also an exception:

"Cannot insert duplicate key row in object 'dbo.Person' with unique index 'IX_Person_TitleAndFirstNameAndMiddleNameAndLastName'. The duplicate key value is ([...]).\r\nThe statement has been terminated."

SharpRepository seems to try to add the referenced entities too, but I cannot find a way to mark the referenced entities as attached via the API of SharpRepository. Could you please provide an example how-to do this?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions