aspnet核心实体框架7自引用“作业”1到多表

问题描述 投票:1回答:1

我有一个包含作业的“作业”表。事实上,乔布斯并不总是一气呵成......你可以找到一份有很多访问的工作。我打算将其表示为另一个工作,但通过自引用linkId链接回原始工作。

我无法使用流畅的API表示这一点。它是一对多关系..一个工作可能有很多访问,因此一些linkId指向原始工作。链接ID将返回到原始作业ID。它也是可选的,因为大多数工作可能一次性完成..

我已经找到了这个,但很难将其他例子变成这个例子,因为很多它们是一对一的,而且那些给出一对一的examples似乎是使用不同的EF6。

我的工作表是:

    using System;

namespace JobsLedger.Model.Entities
{
    public class Job : IEntityBase
    {
        public int Id { get; set; }
        public string Model { get; set; }
        public string Serial { get; set; }
        public string ProblemDetails { get; set; }
        public string SolutionDetails { get; set; }
        public DateTime JobDate { get; set; }
        public int BrandId { get; set; }
        public int JobTypeId { get; set; }
        public int StatusId { get; set; }
        public int ClientId { get; set; }
        public int UserId { get; set; }

        public int? LinkId { get; set; }  //If there are more than one job callout eg back to fit parts.
        public Job MultipleJobVisits { get; set; }
    }
}

我很确定我有这个错误:

        // Job
        modelBuilder.Entity<Job>().Property(j => j.Model).HasMaxLength(100);
        modelBuilder.Entity<Job>().Property(j => j.Serial).IsRequired();
        modelBuilder.Entity<Job>().Property(j => j.ProblemDetails).HasMaxLength(100);
        modelBuilder.Entity<Job>().Property(j => j.SolutionDetails).HasMaxLength(500);
        modelBuilder.Entity<Job>().Property(j => j.JobDate);
        modelBuilder.Entity<Job>().Property(j => j.Notes).HasMaxLength(1000);
        modelBuilder.Entity<Job>().Property(j => j.BrandId);
        modelBuilder.Entity<Job>().Property(j => j.JobTypeId);
        modelBuilder.Entity<Job>().Property(j => j.StatusId);
        modelBuilder.Entity<Job>().Property(j => j.ClientId);
        modelBuilder.Entity<Job>().Property(j => j.UserId);
        modelBuilder.Entity<Job>().HasOne(x => x.Id)
                                  .WithMany(x => x.LinkId)
                                  .ForeignKey(x => x.Id)
                                  .Required(false);

如何在EF7和Fluent API中表示一对多的自引用,哪些是可选的?

编辑:虽然这不提供语法错误,我不得不说我不确定它是否正常

modelBuilder.Entity<Job>().HasMany(j => j.LinkedJobs).WithOne().IsRequired(false);

对此有任何帮助表示赞赏......我发现在如何配置一对多自引用关系方面的知识很少...

c# entity-framework entity-framework-core self-reference ef-fluent-api
1个回答
9
投票

工作类:

public class Job
{
    public int Id { get; set; }

    public int? JobId { get; set; }

    public Job ParentJob { get; set; }

    public ICollection<Job> ChildJobs { get; set; }
}

流畅的API:

modelBuilder.Entity<Job>()
                .HasMany(oj => oj.ChildJobs)
                .WithOne(j => j.ParentJob)
                .HasForeignKey(j => j.JobId);
© www.soinside.com 2019 - 2024. All rights reserved.