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

Cat*_*lin 29 c# entity-framework fluent-interface ef-code-first

我有一个类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
}
Run Code Online (Sandbox Code Playgroud)

是否可以防止从类AddressDetails内部映射"Country"属性Product?(因为我在Product课堂上永远不需要它)

像这样的东西

Property(p => p.AddressDetails.Country).Ignore();
Run Code Online (Sandbox Code Playgroud)

Two*_*-ha 27

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

modelBuilder.Entity<Product>().Ignore(p => p.AddressDetails.Country);
Run Code Online (Sandbox Code Playgroud)

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

  • 不起作用:`表达式'p => p.AddressDetails.Country'不是有效的属性表达式.表达式应该代表一个属性:C#:'t => t.MyProperty'VB.Net:'Function(t)t.MyProperty'. (3认同)
  • `.Ignore(...)`至少可以在EF 6.1.3中正常工作. (2认同)

Mrc*_*ief 15

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

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

public class AddressDetails
{
    public string City { get; set; }

    [NotMapped]
    public string Country { get; set; }
    // other properties
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您的情况Country只有当它是某个其他实体的一部分时才应被排除,那么您对这种方法不满意.


小智 6

如果您使用的是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");
}
Run Code Online (Sandbox Code Playgroud)