EF Code First Fluent API specifying the Foreign Key property

ef-code-first entity-framework

Question

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).

1
44
2/10/2014 2:56:09 PM

Accepted Answer

I believe you should be able to do this:

HasRequired(t => t.Agent).WithMany().HasForeignKey(t => t.AgentId)
66
10/14/2013 12:06:41 PM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow