EF Code First阻止使用Fluent API进行属性映射

我有一个Product类和一个复杂类型的AddressDetails

 public class Product { public Guid Id { get; set; } public AddressDetails AddressDetails { get; set; } } public class AddressDetails { public string City { get; set; } public string Country { get; set; } // other properties } 

是否可以防止从Product类中的AddressDetails映射“Country”属性? (因为我永远不需要它用于Product类)

像这样的东西

 Property(p => p.AddressDetails.Country).Ignore(); 

对于EF5及更早版本:在上下文的DbContext.OnModelCreating覆盖中:

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

对于EF6:你运气不好。 看见先生的回答 。

不幸的是,接受的答案不起作用,至少对EF6不起作用,特别是如果子类不是实体。

我还没有找到任何方法通过流畅的API来做到这一点。 它的唯一工作方式是通过数据注释:

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

注意:如果您的Country应该仅在其属于某个其他实体的情况下被排除,那么您对此方法的运气不佳。

如果您使用的是EntityTypeConfiguration的实现,则可以使用Ignore方法:

 public class SubscriptionMap: EntityTypeConfiguration { // 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"); } 

虽然我意识到这是一个老问题,但答案并没有解决我在EF 6中的问题。

对于EF 6,您需要创建ComplexTypeConfiguration映射。

例:

 public class Workload { public int Id { get; set; } public int ContractId { get; set; } public WorkloadStatus Status {get; set; } public Configruation Configuration { get; set; } } public class Configuration { public int Timeout { get; set; } public bool SaveResults { get; set; } public int UnmappedProperty { get; set; } } public class WorkloadMap : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration { public WorkloadMap() { ToTable("Workload"); HasKey(x => x.Id); } } // Here This is where we mange the Configuration public class ConfigurationMap : ComplexTypeConfiguration { ConfigurationMap() { Property(x => x.TimeOut).HasColumnName("TimeOut"); Ignore(x => x.UnmappedProperty); } } 

如果您的Context手动加载配置,则需要添加新的ComplexMap,如果使用FromAssembly重载,则将使用其余配置对象选择它。

在EF6上,您可以配置复杂类型:

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

这样,财产国家将始终被忽略。

试试这个

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

在类似的情况下,它对我有用。

它也可以在Fluent API中完成,只需在映射中添加以下代码即可

this.Ignore(t => t.Country),在EF6中测试过