我有这样的实体类型:
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()方法映射到数据库字段。
我该怎么做?
答案 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);