外键关系不为主键Id时的设计(特殊)

当外键关系设计不为主键Id时(一般不这样设计)

LibraryEntity

using Volo.Abp.Domain.Entities;

namespace Product.Domain.Entity;

public class LibraryEntity : AggregateRoot<Guid>
{
    public string Name { get; set; }
    public string Location { get; set; }

    /// <summary>
    /// 外键 在Creating显示对应BookEntity的CeShiId
    /// </summary>
    public int TestId { get; set; }
    
    public List<BookEntity> Books { get; set; }

    public LibraryEntity()
    {
        Books = new List<BookEntity>();
    }
}

BookEntity

using Volo.Abp.Domain.Entities;

namespace Product.Domain.Entity;

public class BookEntity : Entity<Guid>
{
    public string Title { get; set; }
    public string Author { get; set; }
    public string PublishYear { get; set; }

    /// <summary>
    /// 外键 在Creating显示对应LibrayEntity的TestId
    /// </summary>
    public int CeShiId { get; set; }
    public LibraryEntity Library { get; set; }
}

这里的LibraryEntity.TestId就是外键Id,对应BookEntity.CeShiId。它需要设计成唯一值
OnModelCreating显示指定他们之间的关系

        builder.Entity<LibraryEntity>(p =>
        {
            p.ToTable("Libraries");
            p.ConfigureByConvention();

            // 指定主键Id
            p.HasKey(x => x.Id);

            // 忽略暂时用不上的字段
            p.Ignore(x => x.ConcurrencyStamp);
            p.Ignore(x => x.ExtraProperties);

            // 配置 LibraryEntity 和 BookEntity 之间的关系
            p.HasMany(l => l.Books) // 一个 LibraryEntity 关联多个 BookEntity
                .WithOne(b => b.Library) // 一个 BookEntity 关联一个 LibraryEntity
                .HasPrincipalKey(b => b.TestId);
        });


        builder.Entity<BookEntity>(p =>
        {
            p.ToTable("Books");
            p.ConfigureByConvention();

            // 指定主键Id
            p.HasKey(x => x.Id);

            // 配置 BookEntity 和 LibraryEntity 之间的关系
            p.HasOne(b => b.Library) // 一个 BookEntity 关联一个 LibraryEntity
                .WithMany(l => l.Books) // 一个 LibraryEntity 关联多个 BookEntity
                .HasForeignKey(b => b.CeShiId); // 使用 CeShiId 作为外键
        });

这是EF的关系发现约定设计,微软常见的四种设计
<navigation property name><principal key property name>
<navigation property name>Id
<principal entity type name><principal key property name>
<principal entity type name>Id

具体参考微软文档

posted @ 2023-07-23 15:03  kele-cc  阅读(69)  评论(0)    收藏  举报