【问题标题】:How to map an Entity to Multiple tables?如何将实体映射到多个表?
【发布时间】:2014-04-04 20:10:18
【问题描述】:

我在现有数据库中使用 Code First,并且有一个必须映射到两个表的实体,我该如何完成?

数据库:

CREATE TABLE Supplier(
    SupplierId bigint identity(1,1) NOT NULL,
    SupplierName varchar(60) NOT NULL
)

CREATE TABLE Customer(
    CustomerId bigint identity(1,1) NOT NULL,
    CustomerName varchar(60) NOT NULL
)

CREATE TABLE SupplierPayments(
    SupplierPaymentNumber bigint NOT NULL,
    SupplierId bigint NOT NULL, 
    PaymentValue decimal(19,4)  NOT NULL
)

CREATE TABLE CustomerPayments(
    CustomerPaymentNumber bigint NOT NULL,
    CustomerId bigint NOT NULL, 
    PaymentValue decimal(19,4)  NOT NULL
)

ALTER TABLE SupplierPayments
ADD CONSTRAINT PK_SupplierPayments
    PRIMARY KEY CLUSTERED (SupplierPaymentNumber, SupplierId ASC);

    ALTER TABLE CustomerPayments
ADD CONSTRAINT PK_CustomerPaymentss
    PRIMARY KEY CLUSTERED (CustomerPaymentNumber, CustomerId ASC);

还有我的实体:

public partial class Supplier{
     public long SupplierId{ get; set; }
     public string Name{ get; set; }
     public virtual List<Payment> Payments{ get; set; }
}

public partial class Customer{
     public long CustomerId{ get; set; }
     public string Name{ get; set; }
     public virtual List<Payment> Payments{ get; set; }
}

public partial class Payment{
     public long PaymentNumber{ get; set; }
     public decimal Value{ get; set; }
}

如何配置(使用 Fluent API)供应商和客户到付款之间的多对一关系?

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    您可能很难维护这样的代码。完全删除 Customer 和 Supplier 类并添加另一个名为 BusinessPartner 的实体可能更明智:

    public partial class BusinessPartner {
        public long Id {get; set; }
        public string Name {get; set; }
        public BusinessPartnerType Type {get; set; }
    }
    
    public enum BusinessPartnerType {
        Customer = 1,
        Supplier = 2
    }
    

    对于 SupplierPayments 和 CustomerPayments - 它们也应替换为一个表,但您不必指定付款类型,因为它已在 BusinessPartner 表中指定。

    【讨论】:

      猜你喜欢
      • 2012-04-21
      • 2015-08-17
      • 2015-01-07
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多