1

I'm trying to map a couple of legacy tables using Entity Framework. The classes look like this...

public class Customer
{
    [Key, Required]
    public string Code { get; set; }

    public string Domain { get; set; }

    public virtual Address BillToAddress { get; set; }

    public virtual ICollection<Address> ShipToAddresses { get; set; }
}


public class Address
{
    [Column(Order = 0), Key, Required]
    public string Code { get; set; }

    [Column(Order = 1), Key, Required]
    public string Domain { get; set; }

    public string Type { get; set; }

    public string CustomerReferenceCode { get; set; }
}

Each Customer has one "BillToAddress" that corresponds with an Address whose CustomerReferenceCode contains the Customer's Code and where the Type field contains the text "Customer"

Each Customer has zero or more "ShipToAddresses" that correspond to Addresses whose CustomerReferenceCode contains the Customer's Code and whose where the Type fields contain the text "Ship-To"

I'm able to reference the BillToAddress by adding

[Key, Required]
[ForeignKey("BillToAddress"), Column(Order = 1)]
public string Code { get; set; }

[ForeignKey("BillToAddress"), Column(Order = 2)]
public string Domain { get; set; }

But I've not been able to figure out how to reference the collection of ShipToAddresses for the customer.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Feckmore
  • 4,322
  • 6
  • 43
  • 51

1 Answers1

1

See this example (note it is separate classes): Fluent NHibernate automap inheritance with subclass relationship

One easy approach might be:

public class Customer
{
[Key, Required]
public string Code { get; set; }

public string Domain { get; set; }

public virtual ICollection<Address> Addresses{ get; set; }

public virtual Address BillToAddress { get { Addresses.Where(n=>n.Type = Address.BillingAddress)).Single(); }

public virtual ICollection<Address> ShipToAddresses { get { Addresses.Where(n=>n.Type = Address.ShipToAddress)); }
}

One additional comment - this is not implicitly forcing your one Billing address business logic as the example you start with does, so you either need to enforce that elsewhere with the above approach. Also, creating two classes and using TPH as described in the example I link to is the approach I would likely take anyway - which would meet your described goal above directly. Also, in between the two, this may work, using the discriminator in the getter of each property directly.

Community
  • 1
  • 1
Matthew
  • 9,851
  • 4
  • 46
  • 77
  • That is a fairly straight-forward solution. We do have a fairly strict separation of model and queries against the EF context. For now, I am implementing something very similar... In the base iqueryable that calls the customer, I am populating the various addresses there. – Feckmore Jan 22 '13 at 15:23
  • So - this was helpful? In that case, glad I could help! – Matthew Jan 22 '13 at 15:40