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

回眸只為那壹抹淺笑 提交于 2019-11-30 06:29:53
Devart

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.

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

Here is an example how to make entity framework use table schemas based on namespace(s) of your models. For example if you have a model RiaLib.Data.Models.Membership.User then corresponding db table will be called [Membership].[User] instead of [dbo].[User].

public class DatabaseContext : DbContext
{
    public DbSet<Membership.User> Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Add(new TableSchemaConvention());

        base.OnModelCreating(modelBuilder);
    }
}

https://github.com/rialib/efextensions > TableSchemaConvention.cs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!