gpt4 book ai didi

c# - 如何首先在 Entity Framework 代码中为每种类型配置多个对象集

转载 作者:太空狗 更新时间:2023-10-29 20:17:30 25 4
gpt4 key购买 nike

我正在使用 Entity Framework 5 code first。在我的数据库中,我有 2 个表,AvailPayPeriodsAvailPayPeriodsWeekly。它们看起来都一样:

Period datetime not null

因为这 2 个表在本质上是相同的,所以我决定创建以下类来表示 2 个中的任意一个:

public class PayPeriod : IEntity
{
public int Id { get; set; }

public DateTime Period { get; set; }
}

我正在努力配置 2。我的数据库上下文类中有以下内容:

public DbSet<PayPeriod> WeeklyPayPeriods { get; set; }
public DbSet<PayPeriod> MonthlyPayPeriods { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new WeeklyPayPeriodConfiguration());
// Haven't yet created the configuration file for monthly pay periods
}

我的 WeeklyPayPeriodConfiguration 类:

class WeeklyPayPeriodConfiguration : EntityTypeConfiguration<PayPeriod>
{
internal WeeklyPayPeriodConfiguration()
{
this.ToTable("AvailPayPeriodsWeekly");
}
}

当我调用我的存储库取回每周支付周期时,我收到以下错误:

Multiple object sets per type are not supported. The object sets 'WeeklyPayPeriods' and 'MonthlyPayPeriods' can both contain instances of type 'ePaySlips.DomainModel.Entities.PayPeriod'.

如何将 2 映射到各自的表?

我是否应该创建名为 WeeklyPayPeriodMonthlyPayPeriod 的独立类?

最佳答案

您可以添加以下类:

public class MonthlyPayPeriod : PayPeriod
{

}

public class WeeklyPayPeriod : PayPeriod
{

}

并将您的 DbContext 修改为:

public DbSet<WeeklyPayPeriod> WeeklyPayPeriods { get; set; }
public DbSet<MnthlyPayPeriod> MonthlyPayPeriods { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<WeeklyPayPeriod>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("AvailPayPeriodsWeekly");
});
modelBuilder.Entity<MonthlyPayPeriod>().Map(m =>
{
m.MapInheritedProperties();
m.ToTable("AvailPayPeriodsMonthly");
});

}

不完美,但可以完成工作。

关于c# - 如何首先在 Entity Framework 代码中为每种类型配置多个对象集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14893446/

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