[英]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
类型,它由两种类型实现: CPF
和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
. TaxNumber
在Person
基础 model 中用作主键,这也是一个抽象类型,由PhysicalPerson
和LegalPerson
两种类型实现。
Knowing that:知道:
When Person
is PhysicalPerson
, TaxNumber
is CPF
.当Person
是PhysicalPerson
时, TaxNumber
是CPF
。
When Person
is LegalPerson
, TaxNumber
is CNPJ
.当Person
是LegalPerson
时, TaxNumber
是CNPJ
。
The problem is when I run DbContext.Persons.Find(CPF)
or DbContext.Persons.Find(CNPJ)
.问题是当我运行DbContext.Persons.Find(CPF)
或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 '. System.ArgumentException: '调用'DbSet.Find'的position 0处的键值是'CPF'类型,与属性类型'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?显然,传递给Find()
的值必须是TaxNumber
类型,但TaxNumber
是抽象类型,无法实例化,在这种情况下如何使用Find()
?
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:更新 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 EF Core 支持使用任何原始类型的属性作为主键,包括string
、Guid
、byte[]
等
Reference: Key types and values参考: 键类型和值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.