EF Core按ID和Type的关系



我使用EF Core (Code first),我需要通过ID和类型在2个表之间建立关系以下是我的类

public class Lead : BaseEntity
{

public string FirstName { get; set; }
public string LastName { get; set; }
public short Status { get; set; }
public short PhoneType { get; set; }
public string Phone { get; set; }
public short EmailType { get; set; }
public string Email { get; set; }
public string Notes { get; set; }

public List<AddressInformation> AddressInformations { get; set; }
}

public class Opportunity : BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<AddressInformation> AddressInformations { get; set; }
}
public class AddressInformationViewModel
{
public int Id { get; set; }
public int SourceID { get; set; }  // in this column i need to store ID for Lead or Oppurtunity
public string RelatedTo { get; set; } // in this column i need to store text "Lead" or "Oppurtunity"
public short AddresType { get; set; }
public string Description { get; set; }
}

AddressInformation类将根据SourceID和RelatedTo列保存Leads或Opportunity的信息

我们如何处理这种关系?当我进行数据迁移时,EF将在Lead表中添加新列,列名"LeadID"我不需要这种方法,有没有办法处理这样的关系

我建议为每个关系考虑一个多对多连接表,而不是在Address中有效地使用SourceId + SourceType关联。即使用LeadAddress表和OpportunityAddress表。对于EF Core 5和EF 6,您可以在没有连接实体的情况下将它们关联起来,只需映射连接表,或者为早期的EF Core创建连接实体,或者如果您需要在关系中添加其他列。

使用特定链接表的主要优点是可以维护FK关系。对于SourceId + SourceType,您不能将SourceId用作Lead和Opportunity的FK,但是对于连接表,LeadId可以FK到Lead,而AddressId可以FK到地址。这有助于保持查询地址相关详细信息的效率。

这种方法的好处或限制是,通过链接表,地址可以合法地分配给潜在客户和机会,或者在潜在客户/机会之间共享。如果您不想支持跨多个实体共享地址,则需要实现检查以防止这种情况。这意味着将地址视为一个独特的位置,而不仅仅是一个特定相关实体的数据容器。例如,123 Smithe St.总是123 Smithe St.为Lead更改地址通常意味着将其与具有不同值的新address对象相关联,而不是编辑123 Smithe St.的值(除非他们实际上意味着更正地址,即123 Smith St.)

SourceId + SourceType可以实现,但AFAIK这将不得不作为独立的不相关实体处理,并与查询手动连接,即:

var query = context.Leads
.Join(context.Addresses.Where(a => a.RelatedTo == "lead"),
l => l.Id,
a => a.SourceId,
(l,a) => new {Lead = l, Addresses = a})
.Single(x => x.Lead.Id == leadId);

随着查询越来越多,处理Join变得越来越复杂,而且我猜你不会得到像lead这样有用的东西。地址在映射/导航属性之外,你可以使用lead。地址或至少引导。使用专用链接表的LeadAddresses

最新更新