【问题标题】:Can a Table Be Split Into EF Classes With a One-To-Many Relationship?可以将表拆分为具有一对多关系的 EF 类吗?
【发布时间】:2017-01-23 21:40:46
【问题描述】:

数据库结构
我有一个非常非规范化的 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;}
}

问题
虽然我找到了关于将表拆分为一对一实体以及将外键数据映射到 EF 中的集合的教程,但我找不到任何关于将列从一个表映射到集合的任何内容。这可能吗,还是我仅限于拆分表格、创建视图或为每列创建一个具有属性的 POCO 类?

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

【问题讨论】:

    标签: c# .net entity-framework table-splitting


    【解决方案1】:

    你的课程应该看起来像链接这个

    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
    }
    

    【讨论】:

    • Mulțumesc 多!一个人将如何写其中之一?
    猜你喜欢
    • 2013-03-23
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    相关资源
    最近更新 更多