使用SqlBulkCopy来向数据库批量插入数据,抛出异常:“Cannot access destination table 'dbo.User'”,求解决方案
数据库情况:
1 连接字符串正确,能正常登陆,使用SQL SERVER MANAGEMENT STUDIO能够正常对表进行增删改查
2 使用LINQ TO SQL 对User表能够正常增、删、改、查
直接上代码:
namespace SqlBulkCopyPractice
{
class Program
{
static string connStr = "Data Source=xxxxxxxx,8087; Initial Catalog=TestDb;User ID=xxxxxx;Password="xxx";
static void Main(string[] args)
{
List<UserInMemory> UserInMemoryList = new List<UserInMemory>();
List<User> UserList = new List<User>();
UserInMemoryList = CreateStringList(10000);//得到列表
foreach (var tmp in UserInMemoryList)
{
User user = new User();
user = ConvertUserInMemoryToUser(tmp);
UserList.Add(user);
}
Stopwatch stopWatch = new Stopwatch();
stopWatch = InsertUsingSqlBulkCopy(UserInMemoryList);
Console.Write("SqlBulkCopy耗时:" + stopWatch.Elapsed.TotalSeconds + "秒");
Console.ReadKey();
}
private static User ConvertUserInMemoryToUser(UserInMemory _userInMemory)
{
User result = new User();
result.ID = _userInMemory.ID;
result.UserName = _userInMemory.UserName;
return result;
}
private static UserInMemory ConvertUserToUserInMemory(User _user)
{
UserInMemory result = new UserInMemory();
if (_user != null)
result.ID = (int)_user.ID;
result.UserName = _user.UserName;
return result;
}
private static List<UserInMemory> CreateStringList(int _ElementNumber)
{
List<UserInMemory> resultList = new List<UserInMemory>();
for (int i = 0; i < _ElementNumber; i++)
{
UserInMemory user = new UserInMemory();
user.ID = i;
user.UserName = "张" + i.ToString() ;
resultList.Add(user);
}
return resultList;
}
private static Stopwatch InsertUsingSqlBulkCopy(List<UserInMemory> list)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("UserName");
for (int i = 0; i < list.Count; i++)
{
DataRow row = dt.NewRow();
row["ID"] = list[i].ID;
row["UserName"] = list[i].UserName;
dt.Rows.Add(row);
}
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connStr))
{
bulkCopy.DestinationTableName = "dbo.User";
bulkCopy.ColumnMappings.Add("ID","ID");
bulkCopy.ColumnMappings.Add("UserName", "UserName");
bulkCopy.WriteToServer(dt);
}
stopWatch.Stop();
return stopWatch;
}
}
struct UserInMemory
{
int iD;
public int ID
{
get { return iD; }
set { iD = value; }
}
string userName;
public string UserName
{
get { return userName; }
set { userName = value; }
}
}
}
------解决思路----------------------
不加dbo的User试过了吗