EF Code First Fluent API specifying the Foreign Key property

ef-code-first entity-framework

Question

I have a class called AgentBalance that is linked to Agent, so:

public class AgentBalance
{
    ...

    public int AgentId { get; set; }

    public virtual Agent Agent { get; set; }

}

By convention, AgentId is recognized as the FK for the Agent relationship, but I want to explicitly state this in the Mapping class to protect myself from changes in the future. I am aware of how to implement this if Agent has a collection of Balances, for example:

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

I don't want the relationship between Agent has not and his collection of Balances to be reverse navigable, though. but not without. I am not given the opportunity to specify when using WithMany in the mapping. HasForeignKey. Is there an alternative? (Note that although I could accomplish this goal via attributes, I prefer to use the fluent API mapping.)

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

Accepted Answer

ZZZ_tmp
66
10/14/2013 12:06:41 PM

Popular Answer

Instead of Fluent API, I favor using Data Annotations for these purposes. It is considerably shorter and simple to understand. Although EF must automatically identify attributes that end in "Id," you can declare them explicitly just to be safe:

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

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

If your FK props do not finish in "Id," you must explicitly declare them, for instance:

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; }

More information is available at 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