Search code examples
entity-frameworkasp.net-web-apimany-to-many

Entity Framework Many to Many and existing data post from angular


Entity Framework from Database First created the Table model classes having many to many relationships in C# WebApi.

Table ACCOUNTS and table METADATA have a many-to-many relationship between them. I want to add a new entry on ACCOUNTS table and link this entry with some existing entries from METADATA table. How can I do this using AngularJS to post data?

I am sending this data on $http:

var account: {
    Title: 'Title',
    User: 'User',
    METADATA: [
    {
        Name: 'value1'
    }, 
    {
        Name: 'value2'
    }]
}

The account variable above is based on ACCOUNTS class which is being read by the C# web api using POST and [FromBody] like this:

    [HttpPost]
    public async Task<IHttpActionResult> Add([FromBody]ACCOUNTS account)
    {                               
        db.ACCOUNTS.Add(account);
        await db.SaveChangesAsync();

        int accountId = account.AccountId;

        return Ok(accountId);
    }

I am getting an error of primary key violation of existence of value1 and value2 on table METADATA. This is correct because the values exist in the table.

But actually I want these values to be linked to the "intermediate table" which links ACCOUNTS and METADATA as many-to-many relationship, and not to be added.

Any solution to this scenario?


Solution

  • Before inserting the passed disconnected account object, you need to map the child METADATA objects to existing database entities. For instance, using something like this:

    var medataNames = account.METADATA.Select(e => e.Name);
    account.METADATA = db.METADATA.Where(e => metadataNames.Contains(e.Name)).ToList();
    db.ACCOUNTS.Add(account);
    // ...