简体   繁体   English

带有 Seed 方法和 NotMapped 属性的 EF Core 2.1

[英]EF Core 2.1 with Seed method and NotMapped attribute

I have a question, why my Strategy property is null, when i getting all DbSet from context?我有一个问题,当我从上下文获取所有DbSet时,为什么我的Strategy属性为空? How to [NotMapped] property make visible in my backend? [NotMapped]属性如何在我的后端可见?

My class looks like this:我的课是这样的:

public class Machine
{
    [Key]
    public int Id { get; set; }
    [NotMapped]
    public WorkStrategy Strategy { get; set; }

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

WorkStrategy is an abstract class: WorkStrategy是一个抽象类:

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:我的Seed方法的一部分,其中我的播种机如下所示:

//Machines
for(int i = 0; i < countOfMachines; i++)
{
    Machine machine = new Machine { Id = i + 1 };
    machine.Strategy = new FarmStrategy;
    modelBuilder.Entity<Machine>().HasData(machine);
}

But when i call Machines from DB:但是当我从数据库调用Machines时:

var machines = _context.Machines;

The Strategy property is null. Strategy属性为空。 Could you tell me, how to attach [NotMapped] property while seeding a db ?你能告诉我,如何在播种 db 时附加[NotMapped]属性吗? Is it possbile?有可能吗?

EDIT编辑

When i want to add WorkStrategy as not "notmapped" i get an error from EF while i adding migration:当我想将WorkStrategy添加为未“未映射”时,我在添加迁移时收到来自 EF 的错误:

The entity type 'WorkStrategy' requires a primary key to be defined实体类型“WorkStrategy”需要定义一个主键

But i dont want to make an table for WorkStrategy.但我不想为 WorkStrategy 做一个表。

EDIT My OnModelCreating in context class:context类中编辑我的OnModelCreating

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

        builder.Seed();
        base.OnModelCreating(builder);
    }

Its not work as [NotMapped]它不能作为[NotMapped]

您可以使用 fluent api ignore 而不是 notmapped

modelBuilder.Entity<Machine>().Ignore(x => x.Strategy );

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.如果您有一个标志,需要哪种类型的策略并根据该标志调整策略属性以初始化策略(如果它为空),您可以使用 Fluent-Api 保留您的 Notmapped-Attribute 或 Ignore-Method。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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