Entity Framework code first: How to ignore classes

后端 未结 2 1859
北荒
北荒 2020-12-15 22:56

This is similar to questions here and here, but those are old and have no good answers.

Let\'s say I have the following classes:

class HairCutStyle {         


        
相关标签:
2条回答
  • 2020-12-15 23:34

    There are three things to ensure:

    1. Make sure you do not expose a DbSet<HairCutStyle> in your DbContext-derived class
    2. Make sure you do not have any mention of HairCutStyle in your OnModelCreating override
    3. Mark your HairCutStyle property using the NotMapped attribute.
    0 讨论(0)
  • 2020-12-15 23:35

    Add a property in CustomerHairCutPreference for HairCutSytleID and then use the [NotMapped] attribute on the HairCutStyle property. Note, however, that you will then be responsible for ensuring that the HairCutStyle and HairCutStyleID stay in sync.

    class CustomerHairCutPreference {
       public int ID { get; set; }
       public Customer Customer { get; set; }
       public int HairCutStyleID {get; set; }
    
       [NotMapped]
       public HairCutStyle HairCutStyle { get; set; }
    }
    

    Alternatively, you can use the FluentAPI to exclude HairCutStyle completely from ever being mapped by Entity Framework, which may be useful if you have multiple classes that link to it.

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        modelBuilder.Ignore<HairCutStyle>();
    }
    
    0 讨论(0)
提交回复
热议问题