如何从实体的id中获得鉴别符?



现在我想知道我的id是发票还是个人发票

individualinvoice.cs

public class IndividualInvoice : Invoice {
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}

invoice.cs

public class Invoice {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; }
[Required]
public string Company { get; set; }
[Required]
public string Address { get; set; }
[Required]
public int HouseNumber { get; set; }
[Required]
public string Zipcode { get; set; }
[Required]
public string City { get; set; }
[Required]
public string Country { get; set; }
[Required]
public string VATNumber { get; set; }
public Customer Customer { get; set; }
[ForeignKey("Customer")]
[Required]
public string CustomerId { get; set; }
}

gingsengdbcontext.cs

public class GingsengDbContext : IdentityDbContext<GingsengUser> {
public DbSet<Gingseng> Gingsengs { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Invoice> Invoices { get; set; }
public DbSet<IndividualInvoice> IndividualInvoices { get; set; }
public GingsengDbContext(DbContextOptions<GingsengDbContext> options) : base(options)
{

}
}

这里是我的控制器,我想知道从id如果id对应于一个单独的发票或只是一个发票?还有比使用singleordefault更简洁的方法吗?

public class InvoicesController : Controller {
private readonly GingsengDbContext context;
private readonly IMapper mapper;
public InvoicesController(GingsengDbContext context, IMapper mapper)
{
this.context = context;
this.mapper = mapper;
}
[HttpGet("{id}")]
public async Task<IActionResult> GetInvoice(string id) {

}
}

好吧,唯一干净的方法是使用所有EF Core支持的继承模型(目前是TPH和TPT)是使用c#is算子。然而,类不能从相同的层次结构中继承其他非抽象类,因为IndividualInvoice是一个Invoice,因此将包括在DbSet<Invoice>和检查Invoice的任何查询(OfType等)中。

所以你可以只检查final类,例如

bool isIndividualInvoice = await context.Invoices
.AnyAsync(e => e.Id == id && e is IndividualInvoice);

是一样的
bool isIndividualInvoice = await context.IndividualInvoices
.AnyAsync(e => e.Id == id);

和类似(使用Set<IndividualInvoice>()Set<Invoice>().OfType<IndividualInvoice>)。

另一个不太干净的选项只适用于TPH是直接检索discriminator属性值。你必须知道它的名称和类型(默认是"Discriminator")和string),并使用特殊的EF.Property方法,类似于:

var type = await context.Invoices
.Where(e => e.Id == id)
.Select(e => EF.Property<string>(e, "Discriminator")) // <--
.FirstOrDefaultAsync();
// here type will be ether null, "Invoice" or "IndividualInvoice"

最新更新