使用实体框架使用Fergin键从其他表中获取数据

时间:2018-08-21 07:54:11

标签: entity-framework entity-framework-6

我遇到了无法访问已删除对象的问题。

表客户

CustomerId | CurrencyId | AreaId 
4          | 1          | 4

表CustomersToArea

CustomerAreaId | AreaId 
1              | 4

我想做的是使用AreaId作为键来获取CurrencyId从表CustomersToArea到Customers表:

public class Customer
{
public int CustomerId {get; set}
public int CurrencyId {get; set}
public int AreaId     {get; set}
}

public class CustomersToArea
{
public int CustomersToAreaId {get; set}
//and here I'd like to have access to Customers
//and be able to get CurrencyId
//I', trying this way, but does not work:
public virtual Customer Customer {get; set;}
}

实际上,我不知道如何告诉实体框架,这两个表都应使用AreaId进行连接。 我不想要任何其他表,如果不可能,可能存在任何解决方法?

1 个答案:

答案 0 :(得分:1)

该模式将指示存在Area表。我不太确定“ CustomerToArea”将扮演什么角色,客户已经拥有AreaId。通常,类似的事情就是多对多联接表。

基于提供的架构,并假设存在一个Area表:映射Customer,Area和CustomerToArea之间的关系。例如:

public class Customer
{
   public int CustomerId {get; set;}
   public int CurrencyId {get; set;} // If there is a currency entity, I'd recommend mapping it instead.
   // ...
   public virtual Area {get; set;}
}

public class Area
{
   public int AreaId {get; set;}
   // ...
   public virtual ICollection<CustomerToArea> CustomerToAreas {get; set;} = new List<CustomerToArea>();
}

public class CustomerToArea
{
  public int CustomerToAreaId {get; set;}
  // ...
  public virtual Area {get; set;}
}

public class CustomerConfiguration : EntityTypeConfiguration<Customer>
{
   public CustomerConfiguration()
   {
      ToTable("Customers");
      HasKey(x => x.CustomerId)
         .Property(x => x.CustomerId)
         .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

      HasRequired(x => x.Area)
         .WithMany()
         .Map(x => x.MapKey("AreaId")); // Maps the FK on Customer without needing to declare it in the entity. If declared, use .HasForeignKey(x => x.AreaId)
   }
}

public class AreaConfiguration : EntityTypeConfiguration<Area>
{
   public AreaConfiguration()
   {
      ToTable("Areas");
      HasKey(x => x.AreaId)
         .Property(x => x.AreaId)
         .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

      HasMany(x => x.CustomerAreas)
         .WithRequired(x => x.Area)
         .Map(x =>x.MapKey("AreaId"); // Maps the FK on CustomerArea.
   }
}

public class CustomerAreaConfiguration : EntityTypeConfiguration<CustomerArea>
{
   public AreaConfiguration()
   {
      ToTable("CustomerAreas");
      HasKey(x => x.CustomerAreaId)
         .Property(x => x.CustomerAreaId)
         .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
   }
}

然后,如果您想通过CustomerAreaId获取客户的CurrencyId ...

int customerAreaId = 12;

var customers = dbContext.Customers
   .Where(x => x.Area.CustomerAreas
      .Any(a => a.CustomerAreaId == customerAreaId))
   .Select(x => x.CurrencyId)
   .ToList();

或者,删除CustomerToArea表,仅将其命名为“ Area”,并在AreaId上带有PK。您为架构概述的内容似乎已损坏。如果没有Area表,并且您看不到添加表,那么我的建议是修复架构关系,而不是破坏EF的关系映射。