编程语言
首页 > 编程语言> > c# – 如何在EF4.3代码优先的情况下映射到复杂类型?

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

作者:互联网

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

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()方法映射到数据库字段.

我怎样才能做到这一点?

解决方法:

因此,而不是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);

标签:c,oracle,entity-framework,entity-framework-4-1,ef-code-first
来源: https://codeday.me/bug/20190530/1182980.html