【发布时间】:2020-03-16 06:44:47
【问题描述】:
我有以下型号:
public class Order
{
public int Id { get; set; }
public ItemType ItemType { get; set; }
public int ItemId { get; set; }
}
public enum ItemType
{
Customer, Organization, Department, //etc
}
ItemId 是单独模型/表的外键。上述模型按原样映射到基础表。
现在我想在加载Order时自动加载相关实体。
映射时是否可以使用复合外键,如:
public class Order
{
public int Id { get; set; }
public ItemType ItemType { get; set; }
public int ItemId { get; set; }
public ItemTypeCustomer => ItemType.Customer;
public ItemTypeOrganization => ItemType.Organization;
public ItemTypeDeparment => ItemType.Department;
public Customer Customer { get; set; }
public Organization Organization { get; set; }
public Department Department { get; set; }
}
modelBuilder.Entity<Order>()
.HasOptional(p => p.Customer)
.WithMany()
.HasForeignKey(p => new { p.ItemTypeCustomer , p.ItemId });
上述方法可行吗?甚至可以使用代码优先构建这样的东西吗?
【问题讨论】:
-
您是否只需要从包含一些相关数据的表中获取值?
-
@picolino 是的。我试图避免使用视图或 sp,然后手动映射属性。
-
我看这个的时间越长,我就越不明白你想要什么。这主要是因为您显示了两个
Order类,其余代码是试探性的,几乎是伪代码。
标签: c# sql-server entity-framework entity-framework-6