gpt4 book ai didi

c# - 如何在 EF4.3 代码优先中映射到复杂类型或从复杂类型映射?

转载 作者:太空狗 更新时间:2023-10-30 00:54:59 25 4
gpt4 key购买 nike

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

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 类,以及 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# - 如何在 EF4.3 代码优先中映射到复杂类型或从复杂类型映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10904298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com