我想在ASP.NET Core中的两列之间建立一对一的关系

时间:2019-09-15 16:14:28

标签: sql-server entity-framework asp.net-core

我有readingjobOrder班。我想在joborderId类的jobOrderjobOrderId类的reading之间创建一种关系。

public class JobOrder
{
    [Key]
    public int Id { get; set; }

    public int JobOrderId { get; set; }
    public DateTime StartDate { get; set; }
    public Nullable<DateTime> EndDate { get; set; }

    public string MachineCode { get; set; }
    public decimal TotalLength { get; set; }
}

public class Reading
{
    public int Id { get; set; }
    public string MachineCode { get; set; }
    public decimal Length { get; set; }
    public bool status { get; set; }
    public DateTime time { get; set; }

    public int JobOrderId { get; set; }
    public JobOrder JobOrder { get; set; }
}

3 个答案:

答案 0 :(得分:1)

最好的方法是查看文档:{​​{3}}

如果按照描述的方式进行操作,则EF将根据其检测外键属性的能力来选择其中一个实体作为从属。如果选择了错误的实体作为从属,则可以使用Fluent API进行更正。

使用Fluent API配置关系时,请使用HasOne和WithOne方法。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Blog>()
        .HasOne(p => p.BlogImage)
        .WithOne(i => i.Blog)
        .HasForeignKey<BlogImage>(b => b.BlogForeignKey);
}

答案 1 :(得分:0)

如果您遵循code first naming conventions,EF将自动发现Key,ForeignKey和Navigation属性:

sizeof(uint8_t) <= sizeof(uint8_t *)

如果您有多个键composite keys来建立关系,则需要手动定义键和外键:

public class JobOrder
{
    // Primary key (can be JobOrderId as well)
    public int Id { get; set; }

    // other fields...

    // Foreign key
    public int ReadingId { get; set; }

    // Navigation property
    public Reading Reading { get; set; }
}

public class Reading
{
    // Primary key (can be ReadingId as well)
    public int Id { get; set; }

    // other fields...

    // Foreign key
    public int JobOrderId { get; set; }

    // Navigation property
    public JobOrder JobOrder { get; set; }
}

答案 2 :(得分:0)

这样,它将在JobOrder和Reading之间建立1对1的关系

public class JobOrder
{
    [Key]
    public int Id { get; set; }

    public int JobOrderId { get; set; }
    public DateTime StartDate { get; set; }
    public Nullable<DateTime> EndDate { get; set; }

    public string MachineCode { get; set; }
    public decimal TotalLength { get; set; }

    public virtual Reading Reading { get; set; }
}

public class Reading
{
    [Key]
    [System.ComponentModel.DataAnnotations.Schema.ForeignKey("JobOrder")]
    public int Id { get; set; }
    public string MachineCode { get; set; }
    public decimal Length { get; set; }
    public bool status { get; set; }
    public DateTime time { get; set; }

    public JobOrder JobOrder { get; set; }
}