حل مشکل حذف منطقی در جداولی که فیلد منحصر به فرد دارند
[Index(nameof(PhoneNumber), IsUnique = true)] public class User { public long Id { get; set; } [Required] [MaxLength(100)] public string FullName { get; set; } = null!; [Required] [MaxLength(11)] public string PhoneNumber { get; set; } = null!; public bool IsDeleted { get; set; } }
در موجودیت User فیلد PhoneNumber منحصر به فرد است.
کاربری با شماره تلفن 123 ثبت نام میکند و بعد حذف میشود
الان شماره تلفن 123 آزاد است و کاربر دیگری میتواند با این شماره ثبت نام کند و این کاربر نیز حذف میشود و یک کاربر جدید با شماره تلفن 123 ثبت نام میکند
FullName PhoneNumber IsDeleted User1 123 True User2 123 True User3 123 False
پس با وجود اینکه شماره تلفن Unique است ولی میتوان شماره تلفن تکراری داشت به شرطی که IsDeleted=True باشد و باید فقط یک شماره تلفن 123 با IsDeleted=False داشت.
برای اینکار از Filter ها استفاده میکنیم و تنها کافیست در فایل Configuration موجودیت User این کد را اضافه کرد
public class UserConfiguration : IEntityTypeConfiguration<User> { public void Configure(EntityTypeBuilder<User> builder) { builder.HasIndex(x => x.PhoneNumber) .HasFilter("[IsDeleted] = 0"); } }
الان شرط Unique بودن فقط در صورتی کار میکند که IsDeleted=False باشد.