Den*_*nov 1 c# entity-framework entity-framework-core entity-framework-migrations
我有这个实体:
[Table("order")]
public class Order
{
[Key]
[Column("id")]
public Guid Id { get; set; }
[MaxLength(128)]
[Column("description")]
public string Description { get; set; }
[ForeignKey("Student")]
[Column("student_id")]
public Guid StudentId { get; set; }
[ForeignKey("Employer")]
[Column("employer_id")]
public Guid EmployerId { get; set; }
[ForeignKey("Customer")]
[Column("customer_id")]
public Guid CustomerId { get; set; }
public virtual Guid Student { get; set; }
public virtual Guid Employer { get; set; }
public virtual Guid Customer { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我看到下一个快照DbContext:
modelBuilder.Entity("DataInterface.Models.Order", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("Description")
.HasColumnName("description")
.HasMaxLength(128);
b.Property<Guid>("StudentId")
.HasColumnName("student_id");
b.Property<Guid>("EmployerId")
.HasColumnName("employer_id");
b.Property<Guid>("CustomerId")
.HasColumnName("customer_id");
b.HasKey("Id");
b.HasIndex("StudentId");
b.HasIndex("EmployerId");
b.HasIndex("CustomerId");
b.ToTable("order");
});
Run Code Online (Sandbox Code Playgroud)
你怎么能看到——一切都很好。但我需要创建一个组合键并删除主键。那么,让我们开始吧。我的实体的新代码(没有Id主键):
[Table("order")]
public class Order
{
[MaxLength(128)]
[Column("description")]
public string Description { get; set; }
[ForeignKey("Student")]
[Column("student_id")]
public Guid StudentId { get; set; }
[ForeignKey("Employer")]
[Column("employer_id")]
public Guid EmployerId { get; set; }
[ForeignKey("Customer")]
[Column("customer_id")]
public Guid CustomerId { get; set; }
public virtual Guid Student { get; set; }
public virtual Guid Employer { get; set; }
public virtual Guid Customer { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
OnModelCreating我向上下文的方法添加了新行为:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>()
.HasKey(x => new { x.StudentId, x.EmployerId, x.CustomerId });
}
Run Code Online (Sandbox Code Playgroud)
当我添加新迁移时,我看到索引StudentId已被删除。我不明白为什么?我的新快照DbContext:
modelBuilder.Entity("DataInterface.Models.Order", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("Description")
.HasColumnName("description")
.HasMaxLength(128);
b.Property<Guid>("StudentId")
.HasColumnName("student_id");
b.Property<Guid>("EmployerId")
.HasColumnName("employer_id");
b.Property<Guid>("CustomerId")
.HasColumnName("customer_id");
b.HasKey("StudentId", "EmployerId", "CustomerId");
b.HasIndex("EmployerId");
b.HasIndex("CustomerId");
b.ToTable("order");
});
Run Code Online (Sandbox Code Playgroud)
为什么三个索引之一被删除?为什么b.HasIndex("StudentId");线路被删除了?怎么了?
注意:我没有看到另一个表中两个字段的复合键存在此问题。
主键由索引强制执行。
StudentId是该索引中的第一列。
它不需要在其上定义另一个索引(这样的索引几乎肯定也是毫无意义的,因为 PK 索引很可能是表的聚集索引,而非聚集索引在其叶子中包含 PK 列)
| 归档时间: |
|
| 查看次数: |
1278 次 |
| 最近记录: |