문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top