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);
}
}
CodePudding user response:
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
.