[英]EF Core: Define foreign key for part of a composite PK using a chained property
I have the following model: 我有以下模型:
internal class SchemaEfEntity
{
[Required]
[MaxLength(128)]
public string Name { get; set; }
[Required]
public DatabaseEfEntity Database { get; set; }
}
internal class DatabaseEfEntity
{
[Required]
public string Name { get; set; }
[Required]
public InstanceEfEntity Instance { get; set; }
public ICollection<SchemaEfEntity> Schemas { get; set; }
}
internal class InstanceEfEntity : IEfIdEntity
{
public long Id { get; set; }
[Required]
public string Name { get; set; }
public ICollection<DatabaseEfEntity> Databases { get; set; }
}
public sealed class MyDbContext : DbContext
{
internal DbSet<InstanceEfEntity> Instances { get; set; }
internal DbSet<DatabaseEfEntity> Databases { get; set; }
internal DbSet<SchemaEfEntity> Schemas { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<InstanceEfEntity>().HasKey(x => x.Id);
modelBuilder.Entity<InstanceEfEntity>().HasIndex(x => x.Name).IsUnique();
modelBuilder.Entity<DatabaseEfEntity>().HasKey(
$"{nameof(DatabaseEfEntity.Instance)}{nameof(InstanceEfEntity.Id)}",
$"{nameof(DatabaseEfEntity.Name)}");
modelBuilder.Entity<SchemaEfEntity>().HasKey(
$"{nameof(SchemaEfEntity.Database)}{nameof(DatabaseEfEntity.Instance)}{nameof(InstanceEfEntity.Id)}",
$"{nameof(SchemaEfEntity.Database)}{nameof(DatabaseEfEntity.Name)}",
$"{nameof(SchemaEfEntity.Name)}");
}
}
The SchemaEfEntity
has a composite PK defined that consists of ( InstanceId
, DatabaseName
and SchemaName
). SchemaEfEntity
具有定义的复合PK,它由( InstanceId
, DatabaseName
和SchemaName
)组成。
I'd like to define a foreign key from schema.InstanceId
to instance.Id
. 我想定义一个从
schema.InstanceId
到instance.Id
的外键。 I've tried this: 我已经试过了:
modelBuilder.Entity<SchemaEfEntity>()
.HasOne(c => c.Database.Instance)
.WithMany()
.HasForeignKey(
$"{nameof(SchemaEfEntity.Database)}{nameof(DatabaseEfEntity.Instance)}{nameof(InstanceEfEntity.Id)}"
);
But getting the below error when creating a migration: 但是在创建迁移时出现以下错误:
The expression 'c => c.Database.Instance' is not a valid property expression.
表达式“ c => c.Database.Instance”不是有效的属性表达式。 The expression should represent a simple property access: 't => t.MyProperty'.
该表达式应表示一个简单的属性访问:“ t => t.MyProperty”。 Parameter name: propertyAccessExpression
参数名称:propertyAccessExpression
Any ideas? 有任何想法吗? Is it possible at all?
有可能吗? Is there a way to specify it "by hand", ie not using the properties chain but just specifying the table and a column as a plain text?
有没有办法手动指定它,即不使用属性链而是仅将表和列指定为纯文本?
It can be done using the following syntax: 可以使用以下语法来完成:
modelBuilder.Entity<SchemaEfEntity>()
.HasOne(typeof(InstanceEfEntity))
.WithMany()
.HasForeignKey(
$"{nameof(SchemaEfEntity.Database)}{nameof(DatabaseEfEntity.Instance)}{nameof(InstanceEfEntity.Id)}")
.OnDelete(DeleteBehavior.Restrict);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.