Entity Framework code first: How to ignore classes

后端 未结 2 1862
北荒
北荒 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: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();
    }
    

提交回复
热议问题