EF Core 2.1 with Seed method and NotMapped attribute

asp.net-core c# entity-framework-core seeding


I have a question, why my Strategy property is null, when i getting all DbSet from context? How to [NotMapped] property make visible in my backend?

My class looks like this:

public class Machine
    public int Id { get; set; }
    public WorkStrategy Strategy { get; set; }

    public double GetManHours() => Strategy.TimeOfWork(HoursPerDay);

WorkStrategy is an abstract class:

public abstract class WorkStrategy
    public abstract double TimeOfWork(double hours);

public class FarmStrategy : WorkStrategy
    public override double TimeOfWork(double hours) => // do things

public class CultivationStrategy : WorkStrategy
    public override double TimeOfWork(double hours) => //do things

Part of my Seed method where i seeding machines looks like this:

for(int i = 0; i < countOfMachines; i++)
    Machine machine = new Machine { Id = i + 1 };
    machine.Strategy = new FarmStrategy;

But when i call Machines from DB:

var machines = _context.Machines;

The Strategy property is null. Could you tell me, how to attach [NotMapped] property while seeding a db ? Is it possbile?


When i want to add WorkStrategy as not "notmapped" i get an error from EF while i adding migration:

The entity type 'WorkStrategy' requires a primary key to be defined

But i dont want to make an table for WorkStrategy.

EDIT My OnModelCreating in context class:

protected override void OnModelCreating(ModelBuilder builder)
        builder.Entity<Machine>().Ignore(x => x.Strategy);


Its not work as [NotMapped]

1/12/2019 9:04:53 PM

Accepted Answer

You can use fluent api ignore instead of notmapped

modelBuilder.Entity<Machine>().Ignore(x => x.Strategy );
1/12/2019 8:54:52 PM

Popular Answer

I think your Problem is not the not mapped Attribute, but the Structure of your Classes. If you had a Flag, which Type of Strategy is needed and adapt the Strategy-Property depending on that Flag to initialize a Strategy if it’s null, you could keep your Notmapped-Attribute or the Ignore-Method with Fluent-Api.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow