I am trying to add an object that has references to other objects in it to my database using EF-Core. These are my two models:
public class Contact : Entity
{
#nullable enable
public string? Name1 { get; set; }
public string? Name2 { get; set; }
public Company? Company { get; set; }
public string? Salutation { get; set; }
public string? Title { get; set; }
public DateTime? Birthday { get; set; }
public string? Address { get; set; }
public string? Postcode { get; set; }
public string? City { get; set; }
public string? Country { get; set; }
public string? Mail { get; set; }
public string? MailSecond { get; set; }
public string? PhoneFixed { get; set; }
public string? PhoneFixedSecond { get; set; }
public string? PhoneMobile { get; set; }
public string? Fax { get; set; }
public string? Url { get; set; }
public string? SkypeName { get; set; }
public bool? IsLead { get; set; }
public string? Remarks { get; set; }
}
public class Company : Entity
{
#nullable enable
public string? Name { get; set; }
public List<Contact>? Contacts { get; set; }
public string? Address { get; set; }
public string? Postcode { get; set; }
public string? City { get; set; }
public string? Country { get; set; }
public string? Url { get; set; }
public string? Remarks { get; set; }
public string? UpdatedAt { get; set; }
}
public class Entity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime? CreatedAt { get; set; }
public DateTime? LastEdited { get; set; }
public string? BexioId { get; set; }
}
This is my DbContext:
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options)
{
}
public DbSet<Company> Companies { get; set; }
public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(ModelBuilder modelbuilder)
{
modelbuilder.Entity<Contact>().ToTable("Contacts"):
modelbuilder.Entity<Company>().ToTable("Companies");
}
}
When trying to insert data using the following code, I get the following error:
public object Add(string values)
{
var newContact = new Models.Contact();
JsonConvert.PopulateObject(values, newContact);
if (!TryValidateModel(newContact))
return BadRequest(ModelState);
_context.Contacts.Add(newContact);
_context.SaveChanges();
return Ok();
}
Microsoft.EntityFrameworkCore.DbUpdateException
HResult=0x80131500
Message=An error occurred while updating the entries. See the inner exception for details.
Source=Microsoft.EntityFrameworkCore.Relational
StackTrace:
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.Execute(IEnumerable`1 commandBatches, IRelationalConnection connection)
at Microsoft.EntityFrameworkCore.Storage.RelationalDatabase.SaveChanges(IList`1 entries)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(IList`1 entriesToSave)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(DbContext _, Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
at Microsoft.EntityFrameworkCore.DbContext.SaveChanges()
at microtom.portal.Controllers.ContactController.Add(String values) in C:\Users\tpeduzzi\Documents\microtom\microtom.portal\Controllers\ContactController.cs:line 38
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeActionMethodAsync>g__Logged|12_1>d.MoveNext()
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1:
SqlException: Cannot insert explicit value for identity column in table 'Companies' when IDENTITY_INSERT is set to OFF.
I don't exactly know what is going on. I believe that the problem is that EF-Core is trying to insert the object in the Company field of the contact object, even though the data is already in the database and the Id field of that company has already been filled out by the database. Can anybody tell me what I am doing wrong? I've been trying to fix this problem for a few days and I am wuite desperate... I am doing exactly what is being told to me online and in person. Thanks in advance!