Again with an outdated database that cannot be modified and using Entity Framework 4.1 with the Fluent API to read only data.
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 only have an additional client.
Note. Phones should only have 0 | 1 customer. I do NOT want much. So I 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 tried a couple of permutations, usually getting the error message "Each property name in the type must be unique."
Thanks for the help.
EDIT WITH ANSWER
, . , ClientPhone.
[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; }
}
[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; }
}
[Table("ClientPhone")]
public class ClientPhone
{
public int ClientID { get; set; }
[Key]
[ForeignKey("Phone")]
public int PhoneID { get; set; }
public virtual Client Client { get; set; }
public virtual Phone Phone { get; set; }
}