4

I've got a entity type like this:

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

The InvoiceNumberSequence looks like this:

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

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

My problem is that I have an existing database that I cannot change and I'm trying to map tables/columns to my domain model. Here's how the table looks:

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

I have a DbContext like this:

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
    }
}

I need to map the InvoiceNumberSequence both directions... 1) from the database field to the InvoiceNumberSequence class, AND 2) from the InvoiceNumberSequence.GetSequence() method to the database field.

How can I do this?

Byron Sommardahl
  • 12,743
  • 15
  • 74
  • 131
  • do you want to map the result from `GetSequence` with a database field? is that it? and I guess you want to store the result in the `INVOICE_SEQ` field right? – Jupaol Jun 05 '12 at 20:31
  • That's 1/2 of it. I also need to map from the database field to my object model as well. – Byron Sommardahl Jun 05 '12 at 20:38

1 Answers1

6

So instead of GetSequence use a property:

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 }
    }
}

And in mapping add:

modelBuilder.ComplexType<InvoiceNumberSequence>()
            .Property(p => p.Sequence)
            .HasColumnName("INVOICE_SEQ");
modelBuilder.ComplexType<InvoiceNumberSequence>()
            .Ignore(p => p.Prefix);
modelBuilder.ComplexType<InvoiceNumberSequence>()
            .Ignore(p => p.Number);
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670