gpt4 book ai didi

c# - EF Fluent api poco 使用现有 Db 生成和映射

转载 作者:太空宇宙 更新时间:2023-11-03 23:20:55 25 4
gpt4 key购买 nike

我有 2 个表,如下所示,我对应该如何创建 poco 类以及如何映射它们感到困惑。

enter image description here

enter image description here

我已经创建了如下的 POCO 类。

public partial class ExpenseIncome
{
public int ID { get; set; }
public int? ExpIncTypeID { get; set; }
public int AccountID { get; set; }
public decimal? Amount { get; set; }
public int? UserID { get; set; }
public int? GroupID { get; set; }
public DateTime? AddedDate { get; set; }
public string Explanation { get; set; }
public int? ParentItemID { get; set; }
public decimal? Balance { get; set; }
public bool? IsActive { get; set; }
public DateTime? ActivationDate { get; set; }
// this is navigation property
public virtual ExpenseIncomeType ExpenseIncomeType { get; set; }
}

其他 POCO 是:

public partial class ExpenseIncomeType
{
public int ID { get; set; }
public string TName { get; set; }
public int? IsExpOrInc { get; set; }
public int? ParentExpTypeID { get; set; }
public decimal? ExpIncTypeDefaultAmount { get; set; }
public string UserGroupUniqueValue { get; set; }
public int? UserGroupID { get; set; }
// this is navigation property
public virtual ExpenseIncome ExpenseIncome { get; set; }
}

所以,我对如何在 DbContextModelCreating(DbModelBuilder modelBuilder) 方法中映射这些类感到困惑?

最佳答案

如果您打算采用 Code First 方法,至少有两种方法可以做到这一点。

  1. 在 DbContext 中,您必须像您所说的那样覆盖 ModelCreating,并为每个实体编写如下内容:
    protected override void OnModelCreating(DbModelBuilder modelBuilder)       {         modelBuilder.Entity<ExpenseIncome>().HasKey(e => e.ID);        modelBuilder.Entity<ExpenseIncomeType>().HasKey(e => e.ID);      }
  1. Create a mapping class derived from EntityTypeConfiguration and in the constructor of that class indicate related mappings.
    public class ExpenseIncomeMap: EntityTypeConfiguration<ExpenseIncome>    {     public RoleConfiguration()      {        HasKey(e => e.ID);        // etc.      }    }

And after this each mapping class should be added to context

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ExpenseIncomeMap());
modelBuilder.Configurations.Add(new ExpenseIncomeTypeMap());
}

DbContext 中的 Poco 模型应该与数据库结构完全匹配,在这种情况下,您不需要生成任何数据库迁移。

关于c# - EF Fluent api poco 使用现有 Db 生成和映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35492746/

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