Reputation: 17491
In this scenario, I have an existing database with three models:
Address
, which has a 'AddressId', 'ParentId', 'City', 'State', etc
Person
, which has a 'PersonId', 'Name', etc.
Company
, which has a 'CompanyId', 'Name', etc.
Because Address
can contain rows for more models than just one table, there's no foreign key; the Address
column 'ParentId' would contain either a 'PersonId' or 'CompanyId'.
To generate my DbContext
, I used Entity Framework Power Tools Beta 2. Due to the lack of referential integrity, the classes it generated for Person
and Company
do not contain a collection of addresses like they should.
How would I go about altering those classes to add in this "Addresses" property, and ensure it's mapped to the Address table correctly?
At the moment I'm doing something like this; I'd rather have the context map it if possible:
public IEnumerable<Address> Addresses
{
get
{
IEnumerable<Address> addresses = null;
using(MyDb db = new MyDb())
{
addresses = db.Addresses.Where(a => a.ParentId == this.PersonId)
}
return addresses;
}
}
Thanks!
Upvotes: 1
Views: 295
Reputation: 46879
If you can, you should add an unique id to the Address table and then store that id with the entity that it belongs to, whether it be a person, company, vendor etc.
If you can't because of the multiple address scenario, then you could create a new table AddressXRef table that stores the GUID's of the entities (vendor, person, company etc), and the GUID of the address; so every entity could have multiple address and EF will be quite happy with this setup as there will be keys all around.
(I'd also want some sort of address type indicator on the Xref table so I knew what kind of address it was, mailing, shipping, etc)
Upvotes: 2
Reputation: 9931
Create partial classes for both Company
and Person
which have that property you have created in it.
public partial class Company
{
public IEnumerable<Address> Addresses { ... }
}
Upvotes: 0