dey.shin
dey.shin

Reputation: 990

Use Default Table Name & Custom Schema w/ EF Code First

Working with EF Code First, I'd like to specify a schema (Data) for tables, but let EF use its default convention to name the tables.

I'm using DataAnnotations.Schema TableAnnotations to set schema.

[Table("Customers", Schema = "Data")]
public class Customer
{
    public int Id{ get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

But this requires me to set Name manually while I want EF to use its convention to name the tables.

I tried to set the Name with an empty string.

[Table("", Schema = "Data")]

That throws the following - very reasonable, expected - error:

The argument 'name' cannot be null, empty or contain only white space.

Is there any way to let EF default to its table name convention while specifying the schema?

Upvotes: 0

Views: 887

Answers (2)

dey.shin
dey.shin

Reputation: 990

Slava Utesinov suggested using modelBuilder.HasDefaultSchema("Data"); to set the default schma.

This will work when there is only one schema that one wishes to set; however will not work when there is more than one schema to apply, without having to set the Table Name manually.

public class ExampleContext: DbContext
{
    public ExampleContext() : base("ExampleContext") { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("Data");
        ///...
    }

Upvotes: 1

dey.shin
dey.shin

Reputation: 990

This cannot be done as Table attribute has only one constructor, which requires Name to be specified.

Please refer to MSDN - TableAttribute Constructor

public TableAttribute(
string name
)

Upvotes: 0

Related Questions