使用 Fluent API 在 Entity Framework 中创建一对多关系

Creating one to many relationship in Entity Framework using Fluent API

我有以下 POCO 类:

public class Client
{
    public string ClientId { get; set; }
    public string CompanyId { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }

    [ForeignKey("AccountId")]
    public virtual ICollection<Note> Notes { get; set; } 
}

public class Note
{
    public decimal NoteId { get; set; } 
    public string AccountId { get; set; }
    public string NoteValue { get; set; }

    [ForeignKey("ClientId")]
    public virtual Client Client { get; set; }
}

和以下映射 类:

    public ClientMap(string schema)
    {
        ToTable("CLIENTS", schema);

        // Primary Key
        HasKey(t => t.ClientId);

        // Properties
        Property(t => t.ClientId)
            .HasColumnName("CLIENT_ID")
            .IsRequired()
            .HasMaxLength(16);

        Property(t => t.CompanyId)
            .HasColumnName("COMPANY_ID")
            .IsRequired()
            .HasMaxLength(16);

        Property(t => t.LastName)
            .HasColumnName("LAST_NAME")
            .IsRequired()
            .HasMaxLength(50);

        Property(t => t.FirstName)
            .HasColumnName("FIRST_NAME")
            .IsRequired()
            .HasMaxLength(50);
    }

    public NoteMap(string schema)
    {
        ToTable("NOTES", schema);

        // Primary Key
        HasKey(t => t.NoteId);

        // Properties
        Property(t => t.NoteId)
            .HasColumnName("NOTE_ID")
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        Property(t => t.AccountId)
            .HasColumnName("ACCOUNT_ID")
            .IsRequired()
            .HasMaxLength(16);

        Property(t => t.NoteValue)
            .HasColumnName("NOTE")
            .HasMaxLength(4000);
    }

在此模型中(使用 Fluent API),客户端和注释之间存在一对多关系。 ClientID是clients中的PK,NoteId是Notes中的PK。数据库中没有外键。 ClientId 映射到注释中的 AccountId

我无法让它工作。当我 运行 它时,我可以取回大部分客户端数据,但是当尝试导航到注释时,我在尝试查看注释时收到功能评估超时错误。我无法让客户和笔记之间的关系发挥作用。我哪里出错了? (我想使用 Fluent API 来做到这一点)

谢谢

您正在尝试创建典型的一对多关系。首先,删除您在模型中使用的数据注释,如果您打算使用 Fluent Api,则不需要它们。其次,在您的 Note 实体

中添加 ClientId FK 属性
public class Note
{
    public decimal NoteId { get; set; } 
    public string AccountId { get; set; }
    public string NoteValue { get; set; }

    //FK property
    public int ClientId{get;set;}

    public virtual Client Client { get; set; }
}

然后,在 NoteMap class 的构造函数中,添加此 Fluent Api 配置:

 HasRequired(n=>n.Client).WithMany(c=>c.Notes).HasForeignKey(n=>n.ClientId);