Again with a legacy database that cannot be changed and using Entity Framework 4.1 with the Fluent API to read data only.
public class Client
{
[Key]
public int ClientID { get; set; }
public string Name { get; set ;}
public virtual ICollection<Phone> Phones { get; set; }
}
public class Phone
{
[Key]
public int PhoneID { get; set; }
public string Number { get; set; }
public virtual Client Client { get; set; }
}
public class ClientPhone
{
[Key]
[Column(Order=0)]
public int ClientID { get; set; }
[Key]
[Column(Order=1)]
public int PhoneID { get; set; }
}
I want the Client to have many Phones, but the Phones should have only an optional Client. Note: Phones should have only 0|1 Client. I do NOT want a many to many. So I've tried the following:
modelBuilder.Entity<Client>()
.HasMany(c => c.Phones)
.WithOptional(p => p.Client)
.Map(m =>
{
m.MapKey("ClientID");
m.ToTable("ClientPhone");
});
modelBuilder.Entity<Phone>()
.HasOptional(p => p.Client)
.WithMany(c => c.Phones)
.Map(m =>
{
m.MapKey("PhoneID");
m.ToTable("ClientPhone");
});
I've tried a couple of permutations usually getting an error about "Each property name in a type must be unique."
Thanks for the help.
EDIT WITH ANSWER
Here are the modifications I made to the entity classes. It is possible to navigate from one Client to many Phones and from one Phone to one Client, but you must go through the ClientPhone join table.
[Table("Client")]
public class Client
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ClientID { get; set; }
public string Name { get; set ;}
public virtual ICollection<Phone> Phones { get; set; } // Client has * Phones
}
[Table("Phone")]
public class Phone
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PhoneID { get; set; }
public string Number { get; set; }
public virtual Client Client { get; set; } // Phone has 0|1 Client
}
[Table("ClientPhone")]
public class ClientPhone
{
// Removed the Key attribute
public int ClientID { get; set; }
[Key] // Left the Key on the 0|1 side
[ForeignKey("Phone")]
public int PhoneID { get; set; }
public virtual Client Client { get; set; } // One Client
public virtual Phone Phone { get; set; } // One Phone
}