我正在构建报告系统,但在将数据保存到数据库(实体拆分)时遇到问题。
我的实体:
public class Report
{
[Key]
public int ReportId { get; set; }
public string Title { get; set; }
public int? DateRange { get; set; }
public int Layout { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public int OwnerId { get; set; }
public DateTime DateCreated { get; set; }
public virtual List<ReportCharts> ReportCharts { get; set; }
public virtual List<ReportElements> ReportElements { get; set; }
}
public class ReportElements
{
[Key, Column(Order = 1)]
public int ReportId { get; set; }
[Key, Column(Order = 2)]
public string ElementName { get; set; }
public Boolean Active { get; set; }
}
//Entity class ReportCharts
public class ReportCharts
{
[Key, Column(Order = 1)]
public int ReportId { get; set; }
[Key, Column(Order = 2)]
public string ChartId { get; set; }
public Boolean Active { get; set; }
}
在我的 DbContext 中:
class EFDbContext : DbContext
{
public DbSet<Report> Reports { get; set; }
protected virtual void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Report>().Property(t => t.ReportId).HasColumnName("ReportId");
modelBuilder.Entity<Report>().Property(t => t.Title).HasColumnName("Title");
modelBuilder.Entity<Report>().Property(t => t.DateRange).HasColumnName("DateRange");
modelBuilder.Entity<Report>().Property(t => t.Layout).HasColumnName("Layout");
modelBuilder.Entity<Report>().Property(t => t.DateFrom).HasColumnName("DateFrom");
modelBuilder.Entity<Report>().Property(t => t.DateTo).HasColumnName("DateTo");
modelBuilder.Entity<Report>().Property(t => t.OwnerId).HasColumnName("OwnerId");
modelBuilder.Entity<Report>().Property(t => t.DateCreated).HasColumnName("DateCreated");
modelBuilder.Entity<Report>().HasMany(t => t.ReportElements).WithRequired().HasForeignKey(c => c.ReportId);
modelBuilder.Entity<Report>().HasMany(t => t.ReportCharts).WithRequired().HasForeignKey(p => p.ReportId);
modelBuilder.Entity<ReportElements>().Property(c => c.ElementName).HasColumnName("ElementName");
modelBuilder.Entity<ReportElements>().HasKey(c => new { c.ReportId, c.ElementName });
modelBuilder.Entity<ReportCharts>().Property(p => p.ChartId).HasColumnName("ChartId");
modelBuilder.Entity<ReportCharts>().HasKey(c => new { c.ReportId, c.ChartId });
}
}
在 EF 存储库中:
public void Save(Report report)
{
assignSettingsToEntity(report);
// ????
context.Reports.Add(report);
context.SaveChanges();
}
//Assign settings to Report Entity
public void assignSettingsToEntity(Report report)
{
report.Title = report.getSettings().title;
report.Layout = report.getSettings().layout;
report.DateRange = report.getSettings().layout;
report.DateFrom = report.getSettings().dateFrom;
report.DateTo = report.getSettings().dateTo;
report.DateCreated = DateTime.Now;
report.OwnerId = 54180;
}
当我使用上述代码保存时,数据仅保存到报告表中。如何修改此代码以将数据保存到所有三个表中。
非常感谢您的帮助