1

I have 2 tables in an existing database:

Table1

[Key] public int Id {get; set;}
public int CustomerID {get; set;}
List<Table2> Table2Items {get; set;}
....


Table2
[Key] public int Id {get; set;}
public int customerid {get; set;}
Table1 Table1Item {get; set;}
...

I want to create a one-to-many relationship, such that each record in table1 can have many associated records in table2.

Its normally straight forward using the primary key field in table1 which matches the foreign key field (customerid) in table 2.

But I want to relate the 2 tables based on the CustomerID in table1 with the customerid in table2.

The following appears to relate the 2 tables by using the customerid field in table2 with the primary key in table1, which is not what I require.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

  modelBuilder.Entity<Table1>()
    .HasMany<Table2>(s => s.Table2Items)
    .WithRequired(s => s.Table1Item)
    .HasForeignKey(s => s.customerid);
}

How can I modify the code shown above to fit my requirements.

Simon Lomax
  • 8,714
  • 8
  • 42
  • 75

1 Answers1

0

What you are trying to achieve is impossible with current version of Entity Framework. Quoting from https://stackoverflow.com/a/7022799/337294:

It is not possible. Relations in EF follows exactly same rules as in the database. It means that principal table must have unique identifier which is referenced by dependent table. In case of database the identifier can be either primary key or unique column(s) of principal table. Otherwise it is not valid relation.

And since Entity Framework does not support unique indexes yet (despite strong demand in their Feature Suggestion page), it has to be the Id property of your Table1 class.

Community
  • 1
  • 1
Kamyar
  • 18,639
  • 9
  • 97
  • 171
  • Thanks Kamyar, no wonder we couldn't do it. Although a colleague did discover that by adding something like this ```modelBuilder.Entity() .Property(x => x.Id).HasColumnName("CustomerID");``` we can trick ```EF``` into using the ```CustomerID``` field instead of the ```Id``` field and in fact it worked. In our situation we will only be ```querying``` this database so this may do the job for us. Thanks again for your help. – Simon Lomax Jan 31 '14 at 08:31
  • @SimonLomax: Glad you got it worked out. P.S. EF 6.1 beta just released with support for Indexes. I still cannot find a way to introduce a non-primary-key field in principal end (using fluent api or data annotation) though. – Kamyar Feb 17 '14 at 13:33