C# 如何在EF Core 2中使用外键作为复合键?

C# 如何在EF Core 2中使用外键作为复合键?,c#,foreign-keys,entity-framework-core,composite-primary-key,ef-core-2.0,C#,Foreign Keys,Entity Framework Core,Composite Primary Key,Ef Core 2.0,我有几个EF Core 2课程。 1) 类Ser 具有作为Guid类型的id。它是一个主键,自动递增 2) SerStaHis类 将SerId作为Guid类型。它是类Ser的外键。它是带有时间戳的主键 有时间戳。它是SerId的主键 我使用efcore2构建上面的两个表。我使用复合键特性将SerStaHis.timestamp和SerStaHis.SerId组合为主键 我还在类Ser中使用ForeignKey属性。 问题是我已经设法将外键映射到类SerStaHis,但是我无法将该外键与S

我有几个EF Core 2课程。 1) 类Ser

  • 具有作为Guid类型的id。它是一个主键,自动递增
2) SerStaHis类

  • 将SerId作为Guid类型。它是类Ser的外键。它是带有时间戳的主键

  • 有时间戳。它是SerId的主键

我使用efcore2构建上面的两个表。我使用复合键特性将SerStaHis.timestamp和SerStaHis.SerId组合为主键

我还在类Ser中使用ForeignKey属性。 问题是我已经设法将外键映射到类SerStaHis,但是我无法将该外键与SerStaHis.timestamp组合作为主键

下面是类Ser、类SerStaHis和OnModelCreating方法的代码片段

public class Ser {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]   // auto-incrementing feature
    public Guid id { get; set; }

    //nav/foreign keys
    [ForeignKey("id")]
    public virtual ICollection<SerStaHis> SerStaHis{ get; set; }
}

public class SerStaHis{
    [Required] // maybe this is wrong as I got a foreign key from Class Ser
    public Guid service_id { get; set; }
    [Required]
    public DateTime timestamp { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);

        // composite primary keys method. // https://docs.microsoft.com/en-us/ef/core/modeling/keys
        modelBuilder.Entity<SerStaHis>()
            .HasKey(c => new {c.service_id, c.timestamp});
    }
公共类服务{
[关键]
[DatabaseGenerated(DatabaseGenerateOptions.Identity)]//自动递增功能
公共Guid id{get;set;}
//导航键/外键
[外国钥匙(“id”)]
公共虚拟ICollection SerStaHis{get;set;}
}
公共级SerStaHis{
[必需]//这可能是错误的,因为我从类Ser获得了一个外键
公共Guid服务_id{get;set;}
[必需]
公共日期时间时间戳{get;set;}
}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder){
基于模型创建(modelBuilder);
//复合主键方法https://docs.microsoft.com/en-us/ef/core/modeling/keys
modelBuilder.Entity()
.HasKey(c=>new{c.service_id,c.timestamp});
}
以下是我迁移到SQL时得到的实际结果:
(来源:)

我在SQL中的预期结果如下:
(来源:)

请让我知道,如果你需要更多的澄清

我可以用FluentAPI方法完成上面的任务吗

如何将外键用作复合主键

谢谢你的改变

[ForeignKey("id")]
public virtual ICollection<SerStaHis> SerStaHis{ get; set; }

如何将serStaHis.service_id中的外键设置为在fluent api和属性中都不可为null?值类型(例如
Guid
int
DateTime
等)始终不可为null,因此无需设置任何内容。如果您有
string
或可空类型(
Guid?
int?
等),并且出于某种原因需要将其设置为必需的,那么可以使用
required
属性或
IsRequired
fluent API。
[ForeignKey("service_id")]
public virtual ICollection<SerStaHis> SerStaHis{ get; set; }
modelBuilder.Entity<Ser>()
    .HasMany(ser => ser.SerStaHis) // collection navigation property
    .WithOne() // no reference navigation property
    .HasForeignKey(serStaHis => serStaHis.service_id); // foreign key property