Waldemar
Waldemar

Reputation: 5513

How to force EF Code First to ignore inheritance?

I've got a base class MyBase which is a part of my data model. I also have classes MyChild1, MyChild2 derived from it in related assemblies.

I want the children to be stored in database and loaded just like MyBase. Also I don't want my entity configuration to know anything about children classes.

Is there any way to force EF to ignore that inheritance and user only base class?

Thanks in advance

Upvotes: 4

Views: 2608

Answers (1)

Dongdong
Dongdong

Reputation: 2508

Here is your case:

public abstract class BaseModel 
{
    public int Id { get; set; }

    public string Name { get; set; }
}

public partial class Child1 : BaseModel
{
     public string Name1 { get; set; }
}


public partial class Child2 : BaseModel 
{
    public string Name2 { get; set; }
}

I guess your data should be similar like this (I am not sure your detail requirements, here is just an example):

public partial class Example<T> where T: BaseModel
{
    public int Id { get; set; }

    public T Data { get; set; } // so here could be any Child of BaseModel
}

public partial class Example: Example<BaseModel> 
{
}
  1. Use ModelBuilder.Ignore<>() Method to let EFCore ignore your children and base.
  2. User PropertyBuilder.HasConversion Method to convert your data to/from database.

Here is sample code:

public class MyDbContext : DbContext
{
    public virtual DbSet<Example> Examples { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        //Let EFCore ignore all models that you don't want it to be a table
        builder.Ignore<BaseModel>();
        builder.Ignore<Child1>();
        builder.Ignore<Child2>();

        builder.Entity<Example>(entity =>
        {
            entity.Property(p => p.Data).HasConversion(
                    x => JsonConvert.SerializeObject(x) //convert TO a json string
                    , x => JsonConvert.DeserializeObject<BaseModel>(x)//convert FROM a json string
                );
        });
    }
}

Upvotes: 3

Related Questions