在一个主要实体和 2 个依赖实体之间创建 1:2 关系

问题描述 投票:0回答:1

使用 EF Core 7,如何定义以下关系?

public class PrincipalEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Name { get; set; }

    // Other properties

    public TheKey PrimaryKey { get; set; }
    public TheKey SecondaryKey { get; set; }
}

public class TheKey
{
    public string PrincipalEntityName { get; set; } // foreign key

    public string Value { get; set; }

    // other properties
}

这样我的

PrincipalEntity
与依赖实体 (
Key
) 的两个实例相关。

我更喜欢在

PrimaryKey
中拥有单独的属性
SecondaryKey
PrincipalEntity
而不是
IEnumerable<TheKey> keys
属性。

c# entity-framework-core
1个回答
0
投票
public class YourDbContext : DbContext
{
    public DbSet<PrincipalEntity> PrincipalEntities { get; set; }
    public DbSet<TheKey> TheKeys { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PrincipalEntity>()
            .HasKey(p => p.Name);

        modelBuilder.Entity<PrincipalEntity>()
            .HasOne(p => p.PrimaryKey)
            .WithOne()
            .HasForeignKey<TheKey>(k => k.PrincipalEntityName)
            .IsRequired(false);

        modelBuilder.Entity<PrincipalEntity>()
            .HasOne(p => p.SecondaryKey)
            .WithOne()
            .HasForeignKey<TheKey>(k => k.PrincipalEntityName)
            .IsRequired(false);

        modelBuilder.Entity<TheKey>()
            .HasKey(k => new { k.PrincipalEntityName, k.Value });
    }
}

public class PrincipalEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string Name { get; set; }

    // Other properties

    public TheKey PrimaryKey { get; set; }

    public TheKey SecondaryKey { get; set; }
}

public class TheKey
{
    public string PrincipalEntityName { get; set; } // foreign key
    public string Value { get; set; }

    // other properties
}

In this setup:

PrincipalEntity class contains two navigation properties (PrimaryKey and SecondaryKey) each representing a one-to-one relationship with TheKey.
The OnModelCreating method configures these relationships using the Fluent API.
The HasKey method is used to specify the primary key for both entities.
HasForeignKey method is used to specify the foreign key relationship between PrincipalEntity and TheKey.
.IsRequired(false) is used because the relationship is optional, considering that you mentioned individual properties PrimaryKey and SecondaryKey in PrincipalEntity rather than a collection.
With these configurations, Entity Framework Core will recognize the relationship between PrincipalEntity and TheKey, and you can work with them accordingly.
© www.soinside.com 2019 - 2024. All rights reserved.