EF Code First prevent property mapping with Fluent API

后端 未结 7 1194
鱼传尺愫
鱼传尺愫 2020-12-29 20:42

I have a class Product and a complex type AddressDetails

public class Product
{
    public Guid Id { get; set; }

    public Addres         


        
相关标签:
7条回答
  • 2020-12-29 20:57

    For EF5 and older: In the DbContext.OnModelCreating override for your context:

    modelBuilder.Entity<Product>().Ignore(p => p.AddressDetails.Country);
    

    For EF6: You're out of luck. See Mrchief's answer.

    0 讨论(0)
  • 2020-12-29 21:00

    If you are using an implementation of EntityTypeConfiguration you can use the Ignore Method:

    public class SubscriptionMap: EntityTypeConfiguration<Subscription>
    {
        // Primary Key
        HasKey(p => p.Id)
    
        Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(p => p.SubscriptionNumber).IsOptional().HasMaxLength(20);
        ...
        ...
    
        Ignore(p => p.SubscriberSignature);
    
        ToTable("Subscriptions");
    }
    
    0 讨论(0)
  • 2020-12-29 21:01

    Try this

    modelBuilder.ComplexType<AddressDetails>().Ignore(p => p.Country);
    

    It worked for me in similar case.

    0 讨论(0)
  • 2020-12-29 21:08

    It can be done in Fluent API as well, just add in the mapping the following code

    this.Ignore(t => t.Country), tested in EF6

    0 讨论(0)
  • 2020-12-29 21:09

    Unfortunately the accepted answer doesn't work, not at least with EF6 and especially if the child class is not an entity.

    I haven't found any way to do this via fluent API. The only way it works is via data annotations:

    public class AddressDetails
    {
        public string City { get; set; }
    
        [NotMapped]
        public string Country { get; set; }
        // other properties
    }
    

    Note: If you have a situation where Country should be excluded only when it is part of certain other entity, then you're out of luck with this approach.

    0 讨论(0)
  • 2020-12-29 21:19

    On EF6 you can configure the complex type:

     modelBuilder.Types<AddressDetails>()
         .Configure(c => c.Ignore(p => p.Country))
    

    That way the property Country will be always ignored.

    0 讨论(0)
提交回复
热议问题