我有2个表,如下所示,我对如何创建poco类以及如何映射它们感到困惑。
我已经创建了如下的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; }
}
所以,我对如何在ModelCreating(DbModelBuilder modelBuilder)
的{{1}}方法中映射这些类感到困惑?
答案 0 :(得分:2)
如果您要采用Code First方法,至少有两种方法可以做到这一点。
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<ExpenseIncome>().HasKey(e => e.ID); modelBuilder.Entity<ExpenseIncomeType>().HasKey(e => e.ID); }
public class ExpenseIncomeMap: EntityTypeConfiguration<ExpenseIncome> { public RoleConfiguration() { HasKey(e => e.ID); // etc. } }
此后,每个映射类都应添加到上下文
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ExpenseIncomeMap());
modelBuilder.Configurations.Add(new ExpenseIncomeTypeMap());
}
DbContext中的Poco模型应该与数据库结构完全匹配,在这种情况下,您不需要生成任何数据库迁移。
答案 1 :(得分:1)
这不是1:1的关联。当然,&#34;很多&#34; ExpenseIncome
可以共享相同的ExpenseIncomeType
。所以映射应该是:
modelBuilder.Entity<ExpenseIncome>()
.HasRequired(e => e.ExpenseIncomeType).WithMany();
public virtual ExpenseIncome ExpenseIncome { get; set; }
中的属性ExpenseIncomeType
应该会消失。
说ExpenseIncome
&#34;有一个&#34;在语义上是正确的。 ExpenseIncomeType
。反过来没有多大意义,虽然技术上,ExpenseIncomeType
可能有ICollection<ExpenseIncome>
。