在ASP.NET EF Core中,使用两个外键组成的复合键时,有时会遇到评估错误的问题。以下是解决此问题的一种方法:
ForeignKey1
和ForeignKey2
,并且它们共同组成了复合键。public class YourEntity
{
public int ForeignKey1 { get; set; }
public int ForeignKey2 { get; set; }
// Other properties
// Define the composite key
[Key]
public int CompositeKey => HashCode.Combine(ForeignKey1, ForeignKey2);
// Navigation properties for the foreign keys
public ForeignKey1Entity ForeignKey1Entity { get; set; }
public ForeignKey2Entity ForeignKey2Entity { get; set; }
}
HasAlternateKey
方法来配置复合键。这将告诉EF Core将这两个外键属性作为复合键。protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasAlternateKey(e => new { e.ForeignKey1, e.ForeignKey2 });
}
Find
方法。var entity = dbContext.YourEntities.Find(foreignKey1Value, foreignKey2Value);
这样,就可以正确评估由两个外键组成的复合键了。