Richard Pawson
Richard Pawson

Reputation: 1516

EF Code First Fluent API specifying the Foreign Key property

I have a class AgentBalance with an association to Agent, thus:

public class AgentBalance
{
    ...

    public int AgentId { get; set; }

    public virtual Agent Agent { get; set; }

}

AgentId is detected as the FK for the Agent relationship by convention, but I want to make it explicit in the Mapping class, to be safer against future changes. If Agent had a collection of Balances then I know how to do this e.g.:

HasRequired(t => t.Agent).WithMany(a => a.Balances).HasForeignKey(t => t.AgentId);

However, Agent does not have a collection of Balances - I don't want that association to be reverse navigable. But without the .WithMany in the mapping I don't get the option to specify .HasForeignKey. Is there another way? (N.B. I know I could also do this using attributes, but I want to use the fluent API mapping).

Upvotes: 44

Views: 34322

Answers (2)

fifonik
fifonik

Reputation: 1606

I prefer to use Data Annotations for these tasks, not Fluent API. It is much shorter end easy to understand. EF must detect properties ended with "Id" automatically, but to be on a safe side you can specify them explicitly:

using System.ComponentModel.DataAnnotations.Schema;
...
public int AgentId { get; set; }

[ForeignKey("AgentId")]
public virtual Agent Agent { get; set; }

You will need to specify them explicitly if your FK prop are not ended with "Id", for example:

public int AgentCode { get; set; }

[ForeignKey("AgentCode")] // now this is needed if you'd like to have FK created
public virtual Agent Agent { get; set; }

You can find more details here: https://msdn.microsoft.com/en-us/data/jj591583.aspx

Upvotes: 1

SOfanatic
SOfanatic

Reputation: 5573

I believe you should be able to do this:

HasRequired(t => t.Agent).WithMany().HasForeignKey(t => t.AgentId)

Upvotes: 69

Related Questions