简体   繁体   中英

EF 6.1 Fluent API: Ignore property of the base class

I have a base class for all entities:

public class BaseClass
{
    public int SomeProperty {get; set;}
}

public class SomeEntity : BaseClass
{
    ...
}

I want to ignore this property in some cases. Could I do in the OnModelCreating method something like this:

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Properties<int>()
                    .Where(p => p.Name == "SomeProperty")
                    .Ignore();
}

?

You could try:

modelBuilder.Entity<SomeEntity>().Ignore(p => p.SomeProperty);

It will cause SomeProperty not to be mapped to SomeEntity .

EDIT: If this property should never be mapped to database you can add NotMapped annotation in your BaseClass :

public class BaseClass
{
    [NotMapped]
    public int SomeProperty {get; set;}
}

This will be the same as ignoring this property in all extending classes.

A late entry here - but in case it's useful...

Having recently encountered similar requirements, I went with this:-

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder mb)
    {
        mb.Types<EntityBase>()
          .Configure(config => config.Ignore(x => x.SomeBaseClassPropertyToIgnore));
    }
}

This will apply the given configuration to all entity types that inherit from EntityBase. The same technique can be used to configure entity types based on an interface they implement (probably a better approach anyway).

Advantages are:-

  • No need to write and maintain the same config code for multiple concrete entities.
  • No need for [NotMapped] attribute, which is less flexible and adds potentially unwanted dependencies.

Note that the targeted types can be filtered further if necessary:-

protected override void OnModelCreating(DbModelBuilder mb)
{
    mb.Types<EntityBase>().Where(t => t != typeof(SpecialExceptionEntity)).Configure(...);
}

Refs:-

https://msdn.microsoft.com/en-us/library/dn235653(v=vs.113).aspx

https://msdn.microsoft.com/en-us/library/dn323206(v=vs.113).aspx

Could you override it?

public class SomeEntity : BaseClass
{    
    [NotMapped]
    public override int SomeProperty { get; set; }
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM