EF Code首先防止使用Fluent API进行属性映射
本文关键字:API Fluent 映射 属性 Code EF | 更新日期: 2023-09-27 18:01:27
我有一个类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
}
是否有可能防止映射"国家"属性从AddressDetails
在Product
类?(因为我永远不会需要它的Product
类)
像这样
Property(p => p.AddressDetails.Country).Ignore();
适用于EF5及以上版本:在您的上下文的DbContext.OnModelCreating
覆盖中:
modelBuilder.Entity<Product>().Ignore(p => p.AddressDetails.Country);
For 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<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");
}
虽然我意识到这是一个老问题,但答案并没有解决我对EF 6的问题。
对于EF 6您需要创建一个ComplexTypeConfiguration Mapping。
的例子:
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<Workload>
{
public WorkloadMap()
{
ToTable("Workload");
HasKey(x => x.Id);
}
}
// Here This is where we mange the Configuration
public class ConfigurationMap : ComplexTypeConfiguration<Configuration>
{
ConfigurationMap()
{
Property(x => x.TimeOut).HasColumnName("TimeOut");
Ignore(x => x.UnmappedProperty);
}
}
如果你的上下文手动加载配置,你需要添加新的ComplexMap,如果你使用FromAssembly重载,它将与其他配置对象一起被拾取。
在EF6上可以配置复杂类型:
modelBuilder.Types<AddressDetails>()
.Configure(c => c.Ignore(p => p.Country))
试试这个
modelBuilder.ComplexType<AddressDetails>().Ignore(p => p.Country);
在类似的情况下它对我有效
这也可以在Fluent API中完成,只需在映射中添加以下代码
。忽略(t => t. country),在EF6中测试