Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring a property in all inherited objects in EF code first

I have the following abstract base class for all my entities in my EF code first model:

public abstract class BaseEntity
{
  public Id {get; set;}  
  public bool IsDeleted {get; set;}  
  ...
}

I wrote following code in my DbContext's OnModelCreating() method to Ignore the IsDeleted

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        ...
        modelBuilder.Types().Configure(c => c.Ignore("IsDeleted"));
        ...
    }

but when it cause following error:

You cannot use Ignore method on the property 'IsDeleted' on type 'MyEntity' because this type inherits from the type 'BaseEntity' where this property is mapped. To exclude this property from your model, use NotMappedAttribute or Ignore method on the base type.

I'm using .NET 4 so I couldn't use [NotMappedAttribute] to ignore IsDeleted, so I used following code:

public partial class BaseEntity_Mapping : EntityTypeConfiguration<BaseEntity> 
{
    public BaseEntity_Mapping()
    {
        this.HasKey(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        this.Ignore(t => t.IsDeleted);
    }
}

and updated the OnCreatingModel() method to:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    ...
    modelBuilder.Configurations.Add(new BaseEntity_Mapping());
    modelBuilder.Types().Configure(c => c.Ignore("IsDeleted"));
    ...
}

but the problem exists yet. Is there any Idea?

like image 621
Masoud Avatar asked Oct 21 '22 05:10

Masoud


1 Answers

This is a confirmed bug in the Entity Framework 5. See this link.

It should have been fixed in EF6. As a workaround: make IsDeleted readonly and provide a SetIsDeleted(bool value) function.

like image 67
Dabblernl Avatar answered Oct 27 '22 16:10

Dabblernl