Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 4: Code First - Creating db in another schema? MapSingleType?

I have a database and I am using two different schemas. Schemas are like namespaces (correct me if I am wrong). This way I have one database and currently two schemas, so the tables in one schema can be named the same as the tables in the other schema because they are in separate schemas.

How do I get EF Code first to talk to a different schema and not the default schema?

Is it something to do with MapSingleType and overriding a method or can I do something else?

like image 905
Martin Avatar asked Jan 30 '11 08:01

Martin


2 Answers

You can implement the following convention:

public class DefaultSchemaConvention :
             IConfigurationConvention<Type, EntityTypeConfiguration>
{
    string defaultSchema;
    public DefaultSchemaConvention(string defaultSchema)
    {
        if (String.IsNullOrWhiteSpace(defaultSchema))
            throw new ArgumentException("defaultSchema");
        this.defaultSchema = defaultSchema;
    }

    void IConfigurationConvention<Type, EntityTypeConfiguration>.Apply(
         Type memberInfo, Func<EntityTypeConfiguration> configuration)
    {
      EntityTypeConfiguration cfg = configuration();
      string tableName = cfg.EntitySetName;
      if (String.IsNullOrEmpty(tableName))
          tableName = memberInfo.Name;
      cfg.ToTable(tableName, this.defaultSchema);
    }
}  

Usage:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.Edm.Db.ColumnTypeCasingConvention>();
    modelBuilder.Conventions.Add(new DefaultSchemaConvention("TEST"));
}  

There is a couple of side notes by Arthur Vickers here concerning TPT inheritance and many-to-many relations.

like image 54
Devart Avatar answered Sep 23 '22 00:09

Devart


I don't know about the CodeFirst model, but the DataAnnotation for "Table" includes a schema option. My code reads like this:

<Table("Product", Schema:="SalesLT")>
Public Class Product

End Class

This helped me deal with alternate schemas

like image 33
Tom Halladay Avatar answered Sep 20 '22 00:09

Tom Halladay