My customers are two kinds, companies and individuals, so I had to use three classes: one for companies, one for individuals, and the third one to join them, so my models are as follow:
public class CustomerCompany
{
public string CustomerId { get; set; }
public string Name { get; set; }
public virtual Customer Customer { get; set; }
}
-
public class CustomerIndividual
{
public string CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Customer Customer { get; set; }
}
-
public class Customer
{
public string CustomerId { get; set; }
public string address { get; set; }
public virtual CustomerCompany Company { get; set; }
public virtual CustomerIndividual Individual { get; set; }
}
Then I configured the one to one relationship as follows:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Customer>(customer =>
{
customer.HasOne(c => c.Company)
.WithOne(cc => cc.Customer)
.HasForeignKey<CustomerCompany>(c => c.CustomerId)
.IsRequired();
customer.HasOne(c => c.Individual)
.WithOne(ci => ci.Customer)
.HasForeignKey<CustomerIndividual>(c => c.CustomerId)
.IsRequired();
});
}
Now when I try to seed data in the following order: 1-CustomerCompanies 2-CustomerIndividuals 3-Customers, I get the following error:
INSERT INTO "CustomerCompanies" ("CustomerId", "Name") VALUES (@p0, @p1); Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 19: 'FOREIGN KEY constraint failed'.
What am I doing wrong here ?
User contributions licensed under CC BY-SA 3.0