简体   繁体   中英

How to use DbSet.Find() with an entity that has an abstract class as key?

I have an abstract TaxNumber type that is implemented by two types: CPF and CNPJ .

TaxNumber is used as a primary key in the Person base model, which is also an abstract type and implemented by two types: PhysicalPerson and LegalPerson .

Knowing that:

When Person is PhysicalPerson , TaxNumber is CPF .

When Person is LegalPerson , TaxNumber is CNPJ .

The problem is when I run DbContext.Persons.Find(CPF) or DbContext.Persons.Find(CNPJ) . The following exception is raised:

System.ArgumentException: 'The key value at position 0 of the call to' DbSet.Find 'was of type' CPF ', which does not match the property type' TaxNumber '.

Apparently, the value passed to Find() must be exactly of type TaxNumber , but TaxNumber is an abstract type and cannot be instantiated, how to use Find() in this scenario?

For better viewing:

public abstract Person 
{
    [Key]
    public TaxNumber TaxNumber { get; set; }
}

public abstract LegalPerson : Person
{
}

public abstract PhysicalPerson : Person
{
}

With the following configuration defined:

modelBuilder.Entity<LegalPerson>()
    .Property(v => v.TaxNumber)
    .HasConversion(
        v => v.Unformatted,
        v => v == null ? null : new CNPJ(v));

modelBuilder.Entity<PhysicalPerson>()
    .Property(v => v.TaxNumber)
    .HasConversion(
        v => v.Unformatted,
        v => v == null ? null : new CPF(v));

Try casting the values as the base type:

DbContext.Persons.Find((TaxNumber)CPF)
DbContext.Persons.Find((TaxNumber)CNPJ)

UPDATE:

Or try declaring the values as the base type:

TaxNumber key = CPF;
DbContext.Persons.Find(key);

UPDATE 2:

Try using a primitive type as the key instead.

EF Core supports using properties of any primitive type as the primary key, including string , Guid , byte[] and others

Reference: Key types and values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM