I'm fairly new to EF Code First and this may (hopefully!) be a simple question.
I have a simple relationship between People and Address:
People
------
PersonID
Name
Address
-------
AddressID
Address1
PersonID
Most times I've had AddressID in my People table; but this db is a bit "backwards", in that it references the PersonID. In my code, I deal with Person objects and want to get their associated Address. The relationship could be 1 person having many addresses, but it's always 1:1. (This is a 3rd party DB - I can't control the schema.)
How would I set up the relationships in Code First to associate Person and Address? I'm using the fluent API, but I don't see a way to set it up without having a key in both entities. Ideally, I would like my entities to be set up like:
Person {
public int PersonID {get;set;}
public string Name {get;set;}
//other person properites
//navigation property
public Address Address {get;set;}
}
Address {
public string Address1 {get;set;}
//other properties for address
//navigation property
public Person Person {get;set;}
}
I've tried a few ways to configure the relationship, but it keeps erroring out. I've tried defining the Address class as a complex type, but since it's a separate table, can that work? Also, I've tried using the HasOptional and WithOptionalDependant, but to no avail.
So any thoughts on how to best configure my EF CF logic to allow Address to be an entity within Person.
Any suggestions or help is greatly appreciated.
UPDATE I tried Mark's suggestion below, but I'm getting a different error. (See my comment)
My Address entity setup sets PersonID as the entity key:
modelBuilder.Entity<Address>()
.HasKey(a => a.PersonID);
modelBuilder.Entity<Address>()
.Property(a => a.PersonID)
.HasColumnName(<my real column name>);
So the entity's key in the DB is PersonID, but it's also a FK back to Person. Is this causing the problem? (Again, not my DB - it's a 3rd party.) Any help is greatly appreciated. Thanks!!