4

我有一个这样的实体类型:

public class Invoice{
    public int Id { get; set; }
    public InvoiceNumberSequence Sequence { get; set; }
    public decimal Amount { get; set; }
}

InvoiceNumberSequence看起来像这样:

public class InvoiceNumberSequence { 
    public string Prefix { get; set; }
    public int Number { get; set; }

    public string GetSequence() {
        return Prefix + Number;
    }
}

我的问题是我有一个无法更改的现有数据库,并且我正在尝试将表/列映射到我的域模型。以下是表格的外观:

[SYSTEMINVOICES]
INVOICE_ID int
INV_TOTAL decimal
INVOICE_SEQ varchar(255)

我有一个DbContext这样的:

public MyDatabaseContext : DbContext {
    public DbSet<Invoice> Invoices { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        modelBuilder.Entity<PredictedHeat>().ToTable("SYSTEMINVOICES");
        modelBuilder.Entity<Invoice>().HasKey(p => p.Id);
        modelBuilder.Entity<Invoice>().Property(p => p.Id).HasColumnName("INVOICE_ID");
        modelBuilder.Entity<Invoice>().Property(p => p.Amount).HasColumnName("INV_TOTAL");        
        //need something here to map my invoice sequence to my database table
    }
}

我需要将 InvoiceNumberSequence 双向映射... 1) 从数据库字段到 InvoiceNumberSequence 类,以及 2) 从 InvoiceNumberSequence.GetSequence() 方法到数据库字段。

我怎样才能做到这一点?

4

1 回答 1

6

所以不要GetSequence使用属性:

public class InvoiceNumberSequence { 
    public string Prefix { get; set; }
    public int Number { get; set; }

    public string Sequence {
        get { retrun Prefix + Number; }
        set { // Add your parsing logic }
    }
}

并在映射中添加:

modelBuilder.ComplexType<InvoiceNumberSequence>()
            .Property(p => p.Sequence)
            .HasColumnName("INVOICE_SEQ");
modelBuilder.ComplexType<InvoiceNumberSequence>()
            .Ignore(p => p.Prefix);
modelBuilder.ComplexType<InvoiceNumberSequence>()
            .Ignore(p => p.Number);
于 2012-06-05T20:59:56.390 回答