I'm working with EF 6 and I need to create a model ignoring nested properties.
I have a model like this (not the same but it's similar)
public class Client
{
public int ID { get; set; }
public string Name { get; set; }
public int? IdEnt { get; set; }
public Enterprise Enterprise { get; set; }
public int? IdContact { get; set; }
public Contact DirectContact { get; set; }
public Client(string Name, Enterprise enterprise, Contact contact)
{
this.Name = Name;
Enterprise = enterprise;
DirectContact = contact;
}
}
public class Contact
{
public int IdContact { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
public class Enterprise
{
public int IdEnt { get; set; }
public string NameEnt { get; set; }
public string Dir { get; set; }
}
Contacts are created when I create a new Client, but Enterprise is an entity that exist in DB, so I only need to connect this properties but when I add a new Client and save changes appears an error indicate I try to insert an Enterprise (DB has automatic primary key in Enterprise table)
This is the transaction that I use to create a Client
bool transaction = false;
string msj = "";
var strategy = Context.Database.CreateExecutionStrategy();
strategy.Execute(() =>
{
using var dbContextTransaction = Context.Database.BeginTransaction();
try
{
Context.Set<Client>().Add(client); // <= client is created with constructor before this part of code
Context.SaveChanges();
dbContextTransaction.Commit();
Transaccion = true;
}
catch (Exception e)
{
dbContextTransaction.Rollback();
msj = e.InnerException.ToString();
/*
Exception:
Cannot insert explicit value for identity column in table 'X' when IDENTITY_INSERT is set to OFF.
I cannot set off this cause I only need connect the entities.
*/
msj = e.Message;
}
});
How I can this?
I'm sorry for my explication and my english if i said something wrong.
Extra: I configured the entities with this code:
public class ClientConfig : IEntityTypeConfiguration<Client>
{
public void Configure(EntityTypeBuilder<Cliente> builder)
{
builder.ToTable("U_Clients");
builder.HasKey(ent => ent.ID);
builder.Property(i => i.ID)
.HasColumnName("IdClient");
builder.HasOne(ent => ent.Contact)
.WithMany()
.HasForeignKey(e=>e.IdContact);
builder.HasOne(ent => ent.Enterprise)
.WithMany()
.HasForeignKey(e=>e.IdEnterprise);
}
}