如何将实体映射到多个表?

时间:2014-02-27 19:26:34

标签: c# entity-framework

我正在将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)供应商和客户之间的多对一关系付款?

1 个答案:

答案 0 :(得分:0)

你可能在维护这样的代码时遇到麻烦。完全删除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表中指定。