0

I am getting this Error:

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

..when I am Trying to insert something into the table "Clients". Every Client has 1 Unterwerk but i am never inserting an Unterwerk in my code.

This is how I insert the client:

public void Insert(Client entity)
{
    _context.Clients.Add(entity);
    _context.SaveChanges();
}

Here's the Client object:

public async void addClient()
        {
            Client client;
            client = new Client();
            client.Hostname = newHostname;
            client.IP = newIP;
            client.MAC = newMAC;
            client.Subnetmask = newSubnet;
            client.Gateway = newGateway;

            using (var repo = new UnterwerkRepository(contextFactory.CreateDbContext()))
            {
                client.Unterwerk = await repo.GetById(newUW);
            }


            using (var repo = new ClientRepository(contextFactory.CreateDbContext()))
            {
                repo.Insert(client);
            }
            
        }
Dale K
  • 25,246
  • 15
  • 42
  • 71
Herbix
  • 35
  • 6

1 Answers1

0

In your client model, you should define the Unterwerk like this (foreign key convention):

class Client 
{
    public Unterwerk Unterwerk {get;set;}
    public int UnterwerkId {get;set;}
}

and when you inserting a client just fill the UnterwerkId property that you got from the UnterwerkRepository.

IamK
  • 2,753
  • 5
  • 30
  • 39
  • 1
    Oh I just set `client.UnterwerkID = newUW` and it works – Herbix Sep 30 '22 at 09:11
  • EF tries to insert that as a new Unterwerk (with the same Id, that is why you got the IDENTITY_INSERT error), just try to fill the UnterwerkId. – IamK Sep 30 '22 at 09:15