我可以在不扩展模型 table 的情况下扩展模型吗?

Can I extend a model without extending its table?

我有一个模型 class 看起来像这样:

public class Foo
{
    [Key] public int Id { get; set; }
}

我在代码的其他地方添加了一个 private subclass:

private class Bar : Foo
{
    public string Name { get; set; }
}

现在,当我构建一个迁移时,我得到了这个:

AddColumn("dbo.Foo", "Name", c => c.String());
AddColumn("dbo.Foo", "Discriminator", c => c.String(nullable: false, maxLength: 128));

我不认为 Entity Framework 会发现 Bar subclass,因为它私下嵌套在 Models 命名空间之外的控制器中.我可以阻止 EF 修改 table 吗?

我尝试 [NotMapped] 忽略 Name 属性,但 EF 仍然添加了一个 Discriminator 列,因为它使用了继承策略。

您可以只对整个 class 使用 [NotMapped] 属性。

这是这个属性的定义:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false)]
public class NotMappedAttribute : Attribute
{
}

AttributeUsage 说你可以在 class 上使用它,而不仅仅是在 属性.

上使用它