如何在EF4.3代码优先的情况下映射到复杂类型?

时间:2012-06-05 20:17:59

标签: c# oracle entity-framework entity-framework-4.1 ef-code-first

我有这样的实体类型:

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类,AND 2)从InvoiceNumberSequence.GetSequence()方法映射到数据库字段。

我该怎么做?

1 个答案:

答案 0 :(得分: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);