复制数据库后无法更新表

时间:2016-11-01 13:48:32

标签: c# sql-server database

我使用c#将我的数据库副本复制到另一个数据库。

一切都很好看。

但是,当我尝试插入一行时,我收到此错误:

System.Data.SqlClient.SqlException:对象数据库架构“dbo”上的INSERT权限被拒绝。

这是我复制数据库的c#代码:

public bool CreateDataBase(string dbName)
{         
        //var connstring = "data source=.;initial catalog=InformedWorker;integrated security=True;";
        var connstring = "Server=localhost;Integrated security=SSPI;database=master";
        var localhost = "localhost";

        try
        {
            Server server = new Server(localhost);



            Microsoft.SqlServer.Management.Smo.Database sourceDatabase = server.Databases["InformedWorkerTemplate"];

            Microsoft.SqlServer.Management.Smo.Database newDatbase = new Microsoft.SqlServer.Management.Smo.Database(server, dbName);


            var clientDBPath = ConfigurationManager.AppSettings["ClientData"];


            newDatbase.FileGroups.Add(new FileGroup(newDatbase, "PRIMARY"));
            DataFile dtPrimary = new DataFile(newDatbase.FileGroups["PRIMARY"], "PriValue", clientDBPath + "\\" + dbName + ".mdf");
            dtPrimary.Size = 77.0 * 1024.0;
            dtPrimary.GrowthType = FileGrowthType.KB;
            dtPrimary.Growth = 1.0 * 1024.0;

            newDatbase.FileGroups["PRIMARY"].Files.Add(dtPrimary);

            LogFile logFile = new LogFile(newDatbase, "Log", clientDBPath + "\\" + dbName + ".ldf");
            logFile.Size = 7.0 * 1024.0;
            logFile.GrowthType = FileGrowthType.Percent;
            logFile.Growth = 10.0;

            newDatbase.LogFiles.Add(logFile);

            newDatbase.Create();

            Transfer transfer = new Transfer(sourceDatabase);
            transfer.CopySchema = true;
            transfer.CopyData = true;
            transfer.Options.DriAllKeys = true;
            transfer.CopyAllObjects = true;
            transfer.CopyAllViews = true;
            transfer.CopyAllDatabaseTriggers = true;
            transfer.CopyAllDefaults = true;
            transfer.CopyAllFullTextCatalogs = true;
            transfer.CopyAllFullTextStopLists = true;
            transfer.CopyAllPartitionFunctions = true;
            transfer.CopyAllPartitionSchemes = true;
            transfer.CopyAllPlanGuides = true;
            transfer.CopyAllRoles = true;
            transfer.CopyAllRules = true;
            transfer.CopyAllSchemas = true;
            transfer.CopyAllSearchPropertyLists = true;
            transfer.CopyAllSequences = true;
            transfer.CopyAllSqlAssemblies = true;
            transfer.CopyAllStoredProcedures = true;
            transfer.CopyAllSynonyms = true;
            transfer.CopyAllTables = true;
            transfer.CopyAllUserDefinedAggregates = true;
            transfer.CopyAllUserDefinedDataTypes = true;
            transfer.CopyAllUserDefinedFunctions = true;
            transfer.CopyAllUserDefinedTableTypes = true;
            transfer.CopyAllUserDefinedTypes = true;
            transfer.CopyAllUsers = true;
            transfer.CopyAllViews = true;
            transfer.CopyAllXmlSchemaCollections = true;
            transfer.CopyAllObjects = true;
            transfer.Options.WithDependencies = true;
            transfer.DestinationDatabase = newDatbase.Name;
            transfer.CopySchema = true;
            transfer.CopyData = true;
            transfer.Options.DriAllKeys = true;

            StringCollection transferScript = transfer.ScriptTransfer();

            using (SqlConnection conn = new SqlConnection(connstring))
            {
                conn.Open();
                using (SqlCommand switchDatabase = new SqlCommand("USE [" + newDatbase.Name + "]", conn))
                {
                    switchDatabase.ExecuteNonQuery();
                }

                foreach (string scriptLine in transferScript)
                {
                    using (SqlCommand scriptCmd = new SqlCommand(scriptLine, conn))//, transaction))
                    {
                        int res = scriptCmd.ExecuteNonQuery();
                    }
                }
            }

            return true;
        }
        catch (Exception ex)
        {
            logging.AddError(ex.ToString());
        }
        return false;
    }

这是我的服务器/ api代码添加一行(我已将数据库绑定到Enitity Framework,因此我更改了数据库)

public void Exchange()
    {
        try
        {
            var query = admin.Subscriptions.Where(d => d.CompanyRef == "56f55e3e-deac-4cde-ae4b-83671363a54e").FirstOrDefault();
            if (query != null)
            {
                o.Database.Connection.Open();
                o.Database.Connection.ChangeDatabase(query.DatabaseName);
                o.Customers.Add(new Customer()
                {
                    CompanyName = "CompanyName",
                    CompanyRef = "CompanyRef",
                    CustomerRef = "CustomerRef",
                    DOE = DateTime.Now,
                    Email = "Email",
                    FName = "FName",
                    MobileNo = "MobileNo",
                    Salutation = "Salutation",
                    ServerRef = "ServerRef",
                    ServerTS = DateTime.Now,
                    SName = "SName",
                    TelephoneNo = "TelephoneNo",
                    Active = true


                });
                o.SaveChanges();
            }
        }
        catch (Exception ex)
        {
            logging.AddError(ex.ToString());
        }
    }

我将所有内容从数据库复制到数据库,所以看不到我还能做什么?

2 个答案:

答案 0 :(得分:2)

您必须为用户和/或权限编写脚本。如果在服务器或实例级别应用安全性,则需要为sql server用户授予对刚刚创建的数据库副本的访问权限。

你快到了。

Managing Users, Roles and Logins

您必须在代码中访问用户凭据,因此请务必小心谨慎。

答案 1 :(得分:0)

看起来我让自己变得比我需要的更难。

我同意其他海报关于这是一个DBA功能,但我要求在托管代码中完成此操作。

另外,感谢罗斯布什(+1)给了我一个关于在哪里看的先发制人。但是,我必须说这些用户已经被复制到新数据库。它只是用户的映射权限,未被转移。

答案很简单:

var localhost = "localhost";
Server srv = new Server(localhost);
Database sourceDatabase = srv.Databases["1407245195"];
var username = @"IIS APPPOOL\DefaultAppPool";
srv.Databases["1407245195"].Roles["db_accessadmin"].AddMember(username);
srv.Databases["1407245195"].Roles["db_backupoperator"].AddMember(username);
srv.Databases["1407245195"].Roles["db_datareader"].AddMember(username);
srv.Databases["1407245195"].Roles["db_datawriter"].AddMember(username);
srv.Databases["1407245195"].Roles["db_ddladmin"].AddMember(username);
srv.Databases["1407245195"].Roles["db_owner"].AddMember(username);
srv.Databases["1407245195"].Roles["db_securityadmin"].AddMember(username);