0

Can someone confirm that I have coded the correct relationship between 2 POCO classes so that I have an Order object that can have 0 or 1 CreditCard objects and a CreditCard object that must belong to an Order (some class properties removed for brevity).

public class Order
{
    public int OrderId { get; set; }
    public string Username { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public decimal Total { get; set; }

    public CreditCard CreditCard { get; set; }
}

public class CreditCard
{
    public int CreditCardId { get; set; }
    public int OrderId { get; set; }
    public CardType Type { get; set; }
    public string Number { get; set; }

    public Order Order { get; set; }
}

In my OnModelCreating method I have the following:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>().HasOptional(or => or.CreditCard).WithRequired(lu => lu.Order);
}

Hopefully the above code is specifying that an Order has an optional CreditCard but the Credit Card requires an Order.

FloatLeft
  • 1,317
  • 3
  • 23
  • 40

2 Answers2

0

In EF, 1:1 and 1:0..1 (and even 0..1:0..1) relationships require that the primary key is shared between all related entities. Your CreditCardId and OrderId values must be the same.

Your configuration seend to specify the relationship correctly, but the OrderId property in CreditCart is redundant and may cause problems. In CreditCard you may need to mark CreditCardId as not being server-generated too.

Community
  • 1
  • 1
Olly
  • 5,966
  • 31
  • 60
0

If you are using an o/r mapper such as Entity Framework or NHibernate, I would model this as one-to-many and use the public property to limit the collection to one item (actually I don't know if that is possible in EF). Basically, I treat this as a 1:n where n is set by a business rule. I don't love this solution but in my experience that's the best way to model it and I haven't found a better solution in the last almost four years.

Community
  • 1
  • 1
Jamie Ide
  • 48,427
  • 16
  • 81
  • 117