开发者

EF Code First and Db Owner

I have a problem that might be simple but I can't find anything about it.

I'm using EF 4.1 Code First on a legacy db. In our development environment, all tables are under "dbo" owner, but in production some are under another user, let's say "myuser".

I am mapping my object with method "ToTable" specifing only the table name without the owner. This way, EF automatically tries to go on [dbo].[TableName] and in production throws an invalid object name error, as the table is [myuser].[TableName]

Is there a way to tell EF to ignore the db owner when mapping tables? I can't change owners in pro开发者_开发技巧duction environment, and I can't replicate for other reasons the production configuration in our development db.

Thanks.


You can set the schema at runtime.

public class YourDbContext : DbContext
{
    public IDbSet<SomeObject> SomeObjects { get; set; }
    public IDbSet<SomeOtherObject> SomeOtherObjects { get; set; }
    public IDbSet<YetAnotherObject> YetMoreObjects { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Configurations.Add(new RuntimeSchemaConfiguration<SomeObject>());
        modelBuilder.Configurations.Add(new RuntimeSchemaConfiguration<SomeOtherObject>());
        modelBuilder.Configurations.Add(new RuntimeSchemaConfiguration<YetAnotherObject>());
    }

    private class RuntimeSchemaConfiguration<T> : EntityTypeConfiguration<T>
        where T : class
    {
        public RuntimeSchemaConfiguration()
        {
            // Rename the schema based on a string
            // from a config file or other source
            var schemaName = GetSchemaNameFromConfigFile();
            ToTable(typeof(T).Name, schemaName);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜