EF Code First Fluent API specifying the Foreign Key property

后端 未结 2 445
滥情空心
滥情空心 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

    0 讨论(0)
  • 2020-12-14 01:03

    I believe you should be able to do this:

    HasRequired(t => t.Agent).WithMany().HasForeignKey(t => t.AgentId)
    
    0 讨论(0)
提交回复
热议问题