I have an existing database in which I use the Entity Framework Code First for matching. The naming convention for the columns is odd, so I decided that I would map the properties of the object manually, and so far this has been good.
The schema for the database is rather strange for me, and definitely not the way I would do it. Unfortunately, I am stuck with this for the time being.
Basically, there is one primary key (AccountNumber), shared by a series of tables, creating a bunch of one-to-one relationships. However, the primary key is also a foreign key column. This is what my objects look like (with the removal of the whole bunch of properties for simplicity). I have included only two objects to simplify them .:
public class Customer { public int AccountNumber { get; set; } public String PhoneNumber { get; set; } ... public virtual Address Address { get; set; } } public class Address { public int AccountNumber { get; set; } public String Name { get; set; } public String Address1 { get; set; } public String City { get; set; } ... public virtual Customer Customer { get; set; } }
Two objects have the same primary key. I created configuration classes to do the mapping as follows:
public class CustomerConfiguration : EntityTypeConfiguration<Customer> { public CustomerConfiguration() : base() { HasKey(p => p.AccountNumber); Property(p => p.AccountNumber). HasColumnName("cm_l_acct"). IsRequired(); Property(p => p.PhoneNumber). HasColumnName("cm_s_phonenumber"); HasRequired(x => x.Address). WithRequiredPrincipal(x => x.Customer). Map(x => x.MapKey("am_l_acct")); } } public class AddressConfiguration : EntityTypeConfiguration<Address> { public AddressConfiguration() : base() { HasKey(p => p.AccountNumber); Property(p => p.AccountNumber). HasColumnName("am_l_acct"). IsRequired(); ... } }
Foreign key mapping is performed on one side only. It looks like it would work if it were not for the fact that the foreign key column is also the primary key of the table. When I try to run a query, I get an error:
(256.6): error 0019: Each property name in the type must be unique. The property name 'am_l_acct' is already defined.
Unfortunately, I cannot pull out the display of the AccountNumber property from the Address object, because this is the primary key.
Is there a way I can perform this mapping, or is this not possible?