How to separate large table into multiple discrete types using EF-Code-First

為{幸葍}努か 提交于 2019-11-30 22:32:09

Edit: Split table to more than two entities in code first is very problematic. It works without any problem when using EDMX.

To make it work you must ensure that each entity used to split table has valid one-to-one relation with all other entities used to split table. That also means spoiling your model with navigation properties and moreover ensuring that during save all navigation properties pointing to the same entity type reference the same instance (otherwise you will get exception during call to SaveChanges).

So the solution for your example should be something like:

public class Campaign {
  [Key]
  public int CampaignId {get;set;}
  public string Name {get;set;}
  public virtual CampaignSurvey Survey {get;set;}
  public virtual CampaignFeedback Feedback {get;set;}
}

public class CampaignSurvey {
  [Key]
  public int CampaignId {get;set;}
  public string Question {get;set;}
  public string Answer {get;set;}

  public virtual CampaignFeedback Feedback {get;set;}
}

public class CampaignFeedback {
  [Key]
  public int CampaignId {get;set;}
  public string Feedback {get;set;}
}

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

    modelBuilder.Entity<Campaign>().HasRequired(c => c.Survey).WithRequiredPrincipal();
    modelBuilder.Entity<Campaign>().HasRequired(c => c.Feedback).WithRequiredPrincipal();
    modelBuilder.Entity<CampaignSurvey>().HasRequired(c => c.Feedback).WithRequiredPrincipal();

    modelBuilder.Entity<Campaign>().ToTable("Campaign");
    modelBuilder.Entity<CampaignSurvey>().ToTable("Campaign");
    modelBuilder.Entity<CampaignFeedback>().ToTable("Campaign");
}

I'm even not sure how this will work in the real scenario. You can find some other problems when using it.

Something I have found that works is to create a view and point your additional entities to that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!