Rudey
Rudey

Reputation: 4965

Can I extend a model without extending its table?

I have a model class that looks like this:

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

Somewhere else in my code I have added a private subclass:

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

Now when I scaffold a migration, I get this:

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

I didn't think Entity Framework would find out there is a Bar subclass, since it's privately nested within a controller, outside of the Models namespace. Can I stop EF from modifying the table?

I tried [NotMapped] to ignore the Name property, but EF still adds a Discriminator column because of the inheritance strategy it uses.

Upvotes: 1

Views: 102

Answers (1)

CodeNotFound
CodeNotFound

Reputation: 23220

You can just use [NotMapped] attribute on your whole class.

This is the definition of this attribute:

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

AttributeUsage say you can use it on class and not just on property.

Upvotes: 3

Related Questions