user3573101
user3573101

Reputation: 69

Custom Primary Key related entity ID property in Entity Framework Code First

I've created a class:

public class Client
{
    public long AccountNumber {get;set;}
    // ...
}

And I'm using non default (Id) primary key:

modelBuilder.Entity<Client>().HasKey(x => x.AccountNumber);

And I've got an entity that is in a relationship with Client

public class Something
{
    public Client Client {get;set;}
}

and I'd like to add property that contains Foreign Key value - ClientAccountNumber

With the default PK (Id, f.e. Client.Id) this works out-of-box:

public class Client 
{
    public long Id {get;set;}
}

public class Something
{
    public Client Client {get;set;}
    public long ClientId {get;set;}
}

With custom PK this doesn't work:

public class Something
{
    public Client Client {get;set;}
    public long ClientAccountNumber {get;set;} // some kind of convention? 
                                               //or explicit configuration?
}

What should be the name of the property, so EF can figure out that this is simply the FK? Is there some kind of naming convention?

Upvotes: 0

Views: 614

Answers (1)

Coding Flow
Coding Flow

Reputation: 21881

You can create a mapping for the foreign key relationship just as you did for the PK.

It is not immediately clear what kind of relationship you want but assuming many to one:

modelBuilder.Entity<Something>()
.HasRequired(x => x.Client)
.WithMany()
.HasForeignKey(x => x.ClientId);

Upvotes: 1

Related Questions