0

I'm having trouble finding the right combination of Fluent methods to map my classes appropriately. Here's basically what I'm trying to do:

Person table: PersonID, HomeAddressID (nullable), WorkAddressID (nullable)
Address table: AddressID, Street, etc...

The Person class has an Address HomeAddress and an Address WorkAddress property, but not the integer properties for the IDs.

The Address class does not have any properties for its related Person entities.

I'm not finding any examples online for this scenario, and I'm just not finding the right combination. Code-first configuration has always done a good job confusing me.

This is the closest to one of the examples I found, but I'm getting Invalid column name 'HomeAddressID', which tells me I'm probably mapping the wrong side of the relationship.

public class PersonConfiguration : EntityTypeConfiguration<Person>
{
    // other mappings

    HasOptional(p => p.HomeAddress)
        .WithOptionalPrincipal()
        .Map(x => x.MapKey("HomeAddressID"));
    HasOptional(p => p.WorkAddress)
        .WithOptionalPrincipal()
        .Map(x => x.MapKey("WorkAddressID"));    
}

Am I on the right track?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Joe Enos
  • 39,478
  • 11
  • 80
  • 136

1 Answers1

1

Could you add the HomeAddress and WorkAddress ids to the person class? If so, this works for me...

public class Person
{
        public int? HomeAddressID { get; set; }
        private Address _homeAddress;
        public Address HomeAddress
        {
            get { return _homeAddress; }
            set
            {
                _homeAddress= value;
                HomeAddressID = value != null ? (int?)value.HomeAddressID : null;
            }
        }
}

public class PersonConfiguration : EntityTypeConfiguration<Person>
{
    HasOptional(a => a.HomeAddress).WithMany().HasForeignKey(p => p.HomeAddressID);
}
Onosa
  • 1,275
  • 1
  • 12
  • 28
  • Looks like that works, thanks, but I am purposely not exposing those properties. In real life, this is an updatable view, and the underlying column is not updated using the view's trigger. I don't want to make it look like the developer can assign a value to that column and expect it to save. – Joe Enos Sep 04 '14 at 21:31