How do I map to and from a complex type in EF4.3 c

2019-04-09 15:57发布

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?

1条回答
淡お忘
2楼-- · 2019-04-09 16:08

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);
查看更多
登录 后发表回答