Gooziec
Gooziec

Reputation: 2776

Entity Framework - how not to add inherited class to the db

I have base class

public class MenuItem
{
        [Key]
        public Guid MenuItemID { get; set; }

        public int MenuType { get; set; }
        public Boolean IsActive { get; set; }
        public String Details { get; set; }
}

and an inherited class

public class MenuItem_URL : MenuItem
{
        public String StartURL { get; set; }
        public Boolean ChangePageEnabled { get; set; }
}

I use Entity Framework code-first.

Now I want to store in DB MenuItem rows but NOT MenuItem_URL.

I add to context

public DbSet<MenuItem> MenuItems { get; set; }

The problem is that in my database creates strange table for MenuItem

[MenuItemID] [uniqueidentifier] NOT NULL,
[MenuType] [int] NOT NULL,
[IsActive] [bit] NOT NULL,
[Details] [nvarchar](max) NULL,
[StartURL] [nvarchar](max) NULL,
[ChangePageEnabled] [bit] NULL

Why does Entity Framework add StartURL and ChangePageEnabled columns? And how to tell him not to? I want to store only base MenuItem objects without any additional data from inherited objects

Upvotes: 1

Views: 70

Answers (2)

Lukas Kabrt
Lukas Kabrt

Reputation: 5489

It is possible to tell EF to ignore a property or the whole class by using the NotMapped attribute

[NotMapped]
public class MenuItem_URL : MenuItem  {
    public String StartURL { get; set; }
    public Boolean ChangePageEnabled { get; set; }
}

or by using the Ignore<T>() method in the fluent configuration.

public class MYContext : DbContext {
    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Ignore<MenuItem_URL>();
    }

...

}

Upvotes: 4

Marc
Marc

Reputation: 3959

Tell Entity Framework that it doesn't need to store the properties.

public class MenuItem_URL : MenuItem
{
    [NotMapped]
    public String StartURL { get; set; }
    [NotMapped]
    public Boolean ChangePageEnabled { get; set; }
}

Upvotes: 0

Related Questions