EntityFramework:是否可以将两个不同的列映射到遵循相同做法的相同 entity/model?

EntityFramework: Is it possible to map two different columns to the same entity/model that follows the same practices?

我正在构建一个应用程序,它从现有的 table 中获取数据,然后将其拆分为多个遵循特定趋势的实体。它适用于管理多个不同机构的出租代理。我确定的一个这样的共享实体是地址,由房东、出租代理和实际 属性 共享,所有这些共享以下属性:

public class Address 
    {
        public string HouseNumber
        public string FlatPosition
        public string AddressLine
        public string Town
        public string County
        public string Postcode
    }

在巨人table中,它们遵循上述架构,但在前面指定了相关名词,例如 "LandlordHouseNumber etc., PropertyHouseNumber etc., LettingAgentHouseNumber etc.,"

是否可以从 table 中获取数据并使用地址 class 进行实例化,同时能够区分它们所代表的实体?还是我需要为每个人提供一个地址 class?

编辑:

据我所知,不可能针对您的情况使用一种模型 class。但是,您可以为所有 Address 模型创建一个通用界面:

public interface IAddress
{
    string HouseNumber { get; set; }
    string FlatPosition { get; set; }
    string AddressLine { get; set; }
    string Town { get; set; }
    string County { get; set; }
    string Postcode { get; set; }
}

然后像这样添加你的模型class:

public class LandLordAddress : IAddress
{
    [Column("LandLordHouseNumber")]
    public string HouseNumber { get; set; }
    ...
}

这样,您至少可以编写更通用的代码来操作这些 classes 的实例。

1。折入数据库

您可以创建一个视图或一个查询,将这些 3x 列折叠成一个合理的一列。

2。检索时折叠

2a Linq-to-sql


//Model
public class Address 
    {
        public string AHouseNumber 
        public string BHouseNumber 
        public string CHouseNumber 
(...)

你可以做一个简单的连接:

await db.Addresses
  .Select( a=> new { Address = AHouseNumber + BHouseNumber + CHouseNumber } )
  .ToListAsync(); 

2b。 运行 自定义查询

正如所怀疑的那样,您想要的是为地址定义一个 Complex Type,然后将属性映射到适当的列。

public class Address 
{
    public string HouseNumber { get; set; }
    public string FlatPosition { get; set; }
    public string AddressLine { get; set; }
    public string Town { get; set; }
    public string County { get; set; }
    public string Postcode { get; set; }
}

public YourEntity
{
    public int Id { get; set; } // or whatever you use
    // other properties

    // complex type properites
    public Address LandlordAddress { get; set; }
    public Address LandlordAgentAddress { get; set; }
}

然后在你的DbContext中配置:

protected void OnModelCreating( DbModelBuilder modelBuilder )
{
    // configure like an entity but use .ComplexType<>()
    modelBuilder.ComplexType<Address>()
        // e.g. set max size of one of the properties
        .Property( a => a.Postcode )
        .HasMaxLength( 10 );
    // etc.

    // map properties to columns if you don't want to use default naming convention
    modelBuilder.Entity<YourEntityType>()
        .Property( yet => yet.LandlordAddress.Postcode )
        .HasColumnName( "LandlordPostcode" );

    modelBuilder.Entity<YourEntityType>()
        .Property( yet => yet.LandordAgentAddress.Postcode )
        .HasColumnName( "LandlordAgentPostcode" );
}