Reputation: 1271
Dear Entity experts and others,
I have the following entities,
Base class Individual:
public abstract class Individual
{
[Key]
public int IndividualID { get; set; }
... other properties
}
Yogi:
[Table("Yogis")]
public class Yogi : Individual
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public DateTime Birthdate { get; set; }
}
Customer:
[Table("Customers")]
public class Customer : Individual
{
public string Name { get; set; }
[ForeignKey("VATID")] // tried with and without
public virtual VAT VAT { get; set; }
}
VAT:
public class VAT
{
[Key]
public int VATID { get; set; }
[Required]
public virtual Customer VATHolder { get; set; }
... other properties
}
DbContext:
public DbSet<Individual> Individuals { get; set; }
public DbSet<VAT> VATS { get; set; }
So the above creates a table VAT where there VATID is 2 to start with which should be 1 instead, I don't understand why this happens, this should be 1, isn't it? Also, there is no reference anywhere in any table that references Customer & VAT, how can I create a separate table VAT_Customer where you have a VATID & CustomerID ?
This is how i create and insert the entity Customer:
VAT vat = new VAT("123456789");
DataBaseHandler.InsertIndividual(new Customer("Customer name", vat,...));
Insert Function:
public static void InsertIndividual(Individual individual)
{
using (MyDbContext ctx = new MyDbContext())
{
ctx.Individuals.Add(individual);
ctx.SaveChanges();
}
}
I have tried several ways (EXAMPLES HERE) but I prefer the TPT way, having a separate view of any entity or relations between entities. What am I doing wrong and how would I achieve the desired result? Let me know if I can clarify anything. Thank you in advance for any help or suggestions!
Kind regards!
Upvotes: 0
Views: 54
Reputation: 172
Your ForeignKey placement should look something like this if you wanna have 1:1 Relationship :
enter code here
[ForeignKey("VAT")]
public virtual int VATId { get; set; }
public virtual VAT VAT { get; set; }
Name in the ForeignKey is same as your class.
hope this can help
Upvotes: 1