【发布时间】:2019-08-08 11:28:27
【问题描述】:
我继承了一个 SQL Server 数据库,其中原始开发人员使用单个表来表示所有“查找”类型,而不是为每个类型指定一个表...
create table Lookup (
LookupID int,
LookupType int,
LookupKey int,
LookupValue varchar(50)
)
然后使用该表(例如)根据 LookupType 提供不同的列表,因此您会看到诸如...的数据。
ID Type Key Value
1 1 1 Mr
2 1 2 Mrs
3 1 3 Miss
4 2 1 Dog
5 2 2 Cat
6 2 3 Hamster
我需要将此表与 Entity Framework Core 一起使用,因为我希望能够在查询数据时拉回查找值。以下表为例...
create table Customer (
CustomerID int,
CustomerTitleID int, <- LookupType = 1
PetTypeID int -- LookupType = 2
)
数据看起来像......
ID TitleID PetTypeID
1 1 1
我可以定义一个“查找”类...
public class Lookup {
public int LookupID {get; set;}
public int LookupTypeID {get; set;}
public int LookupKey {get; set;}
public string LookupValue {get; set;}
}
我可以定义一个“客户”类...
public class Customer {
public int CustomerID {get; set;}
public Lookup CustomerTitle {get; set;}
public int CustomerTitleID {get; set;}
public Lookup PetType {get; set;}
public int PetTypeID {get; set;}
}
问题是,虽然(在 DbContext.OnModelCreating 中)我可以为客户/查找关系指定一个“主键”...
entity<Customer>().HasOne<Lookup>(c => c.CustomerTitle).WithMany().WithForeignKey(c => c.CustomerTitleID).WithPrincipleKey(l => l.LookupKey);
entity<Customer>().HasOne<Lookup>(c => c.PetType).WithMany().WithForeignKey(c => c.PetTypeID).WithPrincipleKey(l => l.LookupKey);
我找不到任何方法为每个“查找”类设置过滤器以通过“查找类型ID”来限制它。
我已尝试创建自定义“PetType”类并将其与“查找”以及过滤器(在 DbContext.OnModelCreating 中)关联...
entity.HasQueryFilter(lookup => lookup.LookupType == 2);
但是 EF 不喜欢将多个实体类型与表关联,除非实体类型也相关(“PetType”必须从“Lookup”继承)。
然后我从“Lookup”继承了那个自定义的“PetType”类并尝试了相同的过滤器......
entity.HasQueryFilter(petType=> petType.LookupType == 2);
但 EF 只允许在根级别进行这样的过滤器。
我也尝试过使用视图,但是虽然 DbSet 实体可以是 DbQuery 实体的子属性,但它似乎不能反过来工作。
我错过了另一种方式吗?我希望能够实现的最终结果是..
from customer in dbContext.Customers
.Select new
{
customer.CustomerID,
Title = customer.CustomerTitle.LookupValue,
PetType = customer.PetType.LookupValue
}
并让 EF 自动对每个 Lookup 应用过滤器(显然由我指定),以便选择正确的行。
【问题讨论】:
标签: entity-framework ef-core-2.2