简体   繁体   中英

Entity Framework add object to new many to many Table Relation Error

I have created a new many to many relation on my database between the tables "Items" and "Itemattributes".

Models:

Item.cs

public class Item
{
    [Key]
    public int ItemCode { get; set; }
    public string ItemName { get; set; }
    public ICollection<ItemAttribute> ItemAttributes { get; set; }
}

ItemAttribute.cs

public class ItemAttribute
{
    [Key]
    public int ItemAttributeCode { get; set; }
    public string Title { get; set; }
    public ICollection<Item> Items { get; set; }
}

Data Context

public DbSet<Item> Items { get; set; }
public DbSet<ItemAttribute> ItemAttributes { get; set; }

Using Commands in package manager console:

Add-Migration FunnyNameForMigration
Update-Database 

Entity Framework creates a Table to Connect the "Items" with the "ItemAttributes" Table, "ItemsItemAttributes". When i try to create a new Item with 2 ItemAttributes by using the ItemController:

[HttpPost]
    public async Task<IActionResult> Post([Bind("ItemCode")] Item item)
    {
        _context.Items.Add(item);
        await _context.SaveChangesAsync();
        return Ok(item.ItemCode);
    }

I get the Error:

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'ItemAttributes' when IDENTITY_INSERT is set to OFF.

I guessed that the Item / Itemattribute relation is only on the new "ItemsItemAttributes" Table, why is Entity Framework is trying to add something on the "Itemattribute" table? And how can i add a new Item with ItemAttributes?

Update

When I manually insert new connections between the tables "Item" and "Itemattribute" in table "ItemItemattribute", it works fine. I suspect there is a problem with the automatic insertion of entity framework.

Nugets: Nugets

You have to turn Identity on for your PK fields in Items and ItemAttributes:

[DatabaseGeneratedOption.Identity]
public int ItemId {get;set;}

[DatabaseGeneratedOption.Identity]
public int ItemAttributesId {get;set;}

I think that you're sending the ItemCode or ItemAttributeCode field in the body of your POST request.

You cannot do it, because these fields are autoincrement and managed by default.
Try to send the model without them.

Cannot insert explicit value for identity column in table 'ItemAttributes' when IDENTITY_INSERT is set to OFF.

The error means do not post ItemAttributeCode specific value when you create a new Item with ItemAttributes .

Just post data like below(use Postman as a example):

在此处输入图像描述

Besides, if you use [Bind("ItemCode")] , it will only bind ItemCode property data to Item and this attribute binds the data from form.

Result Display:

在此处输入图像描述

Environment:

I use Ef Core version 5.0.6 .

I have no solution for my problem. Anyway, because the communication table is working, i update the table manually. Bad workaround.

[HttpPut]
    public async Task<IActionResult> Put(Item item)
    {
        if (item.ItemAttributes != null)
        {
            string delete_sql = $"DELETE FROM ItemItemAttribute WHERE ItemsItemCode = '{item.ItemCode}'";
            _context.Database.ExecuteSqlRaw(delete_sql);
            
            foreach (ItemAttribute itemAttribute in item.ItemAttributes)
            {
                    string create_sql = $"INSERT INTO ItemItemAttribute (ItemAttributesItemAttributeCode, ItemsItemCode) VALUES ('{itemAttribute.ItemAttributeCode}', '{item.ItemCode}')";
                    _context.Database.ExecuteSqlRaw(create_sql);
            }
            item.ItemAttributes.Clear();
        }
        _context.Entry(item).State = EntityState.Modified;
        await _context.SaveChangesAsync();
        return NoContent();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM