.net 表可以拆分为具有一对多关系的EF类吗?

k2fxgqgv  于 12个月前  发布在  .NET
关注(0)|答案(1)|浏览(143)

数据库结构

我有一个非常非规范化的SQL表,结构如下:

CREATE TABLE logistix.shipments
(
    shipment_id INT NOT NULL PRIMARY KEY,
    destination_id NVARCHAR(15) NOT NULL PRIMARY KEY,
    pallet_id INT NOT NULL PRIMARY KEY,
    destination_order INT NOT NULL,
    pallet_description NVARCHAR(40) NOT NULL
)

字符串
虽然每个特定记录都是唯一的,但一次装运可以有多个托盘前往多个目的地。

.NET接口

这将由EF对象操纵,我想像这样构造:

class ShippingContext : DbContext
{
        public virtual DbSet<Shipment> Shipments {get; set;}
}

class Shipment
{
    int ShipmentId {get; set;}
    List<Destination> ShipmentStops {get; set;}
}

class Destination
{
    string DestinationId {get; set;}
    int DestinationOrder {get; set;}
    List<Pallet> Pallets {get; set;}
}

class Pallet
{
    int PalletId {get; set;}
    string PalletDescription {get; set;}
}

  • 问题 *

虽然我已经找到了关于将表拆分为一对一实体以及将外键数据Map到EF中的集合的教程,但我找不到任何关于将一个表中的列Map到集合的教程。这可能吗?或者我仅限于拆分表,创建视图,或者为每个列创建一个POCO类?

最终事项

另一个应用程序将访问SQL表以生成关于任意数量的装运的报告,因此出于性能考虑,Powers That Be选择使用非规范化的表,而不是一套规范化的表和视图,这将需要更长的时间来检索。

pkwftd7m

pkwftd7m1#

您的类应该看起来与此

public class ShipmnetContext : DbContext
{
    public DbSet<Shipment> Shipments { get; set; }
    public DbSet<Destination> Destinations { get; set; }
    public DbSet<Pallet> Pallets { get; set; }  
}

public class Shipment
{
    public int ShipmentId { get; set; }
    public ICollection<Destination> ShipmentStops { get; set; }

    public Shipment()
    {
        ShipmentStops = new HashSet<Destination>();
    }
}

public class Destination
{
    [Key]
    public string DestinationId { get; set; }
    public int DestinationOrder { get; set; }
    //[Required]
    public Shipment Shipment { get; set; } //Foreign key to Shipment table, make property NotNull by adding [Required] attribute
    public ICollection<Pallet> Pallets { get; set; }

    public Destination()
    {
        Pallets = new HashSet<Pallet>();
    }
}

public class Pallet
{
    public int PalletId { get; set; }
    public string PalletDescription { get; set; }
    public Destination Destination { get; set; } //Foreign key to Destination table
}

字符串

相关问题