EF Code First Fluent API specifying the Foreign Key property

后端 未结 2 446
滥情空心
滥情空心 2020-12-14 00:02

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

public class AgentBalance
{
    ...

    public int AgentId { get; set; }

    public virtual         


        
2条回答
  •  独厮守ぢ
    2020-12-14 00:57

    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

提交回复
热议问题