保存c#中同一个类的两个数组



我有这种情况,我只有一个类:CUSTOMER,其中包含多个数组ADDRESSPRIVACY。如何同时插入两个数组呢?

这是json客户类

"customer": {               
"address": [
{ 
"city": "California",
"country": "USA"
}
],
"privacy": [
{
"username": "James",
"password": "123"
}
]
}

这是我的代码部分。但是我一直得到' host variables的值不够'error

//insert
command= new OdbcCommand("INSERT INTO customer"
+ "(@city,@country,@username,@password)"
+ "VALUES(?,?,?,?)", DbConnection);
command.Connection = DbConnection;
command.Transaction = transaction;
command.CommandType = System.Data.CommandType.StoredProcedure;
//add values
//customer address[]
foreach (var customer_address in customer.address)
{           
DbCommandInsertLeads.Parameters.AddWithValue("@city", (object)customer_address.city?? DBNull.Value);                 
DbCommandInsertLeads.Parameters.AddWithValue("@country", (object)customer_address.country ?? DBNull.Value);
}
//customer privacy[]
foreach (var customer_privacy in customer.privacy)
{                 
DbCommandInsertLeads.Parameters.AddWithValue("@username", (object)customer_privacy.username?? DBNull.Value);                                 
DbCommandInsertLeads.Parameters.AddWithValue("@password", (object)customer_privacy.password?? DBNull.Value);
}

Json CUSTOMER类的映射是这样的

public class Address
{
public string city { get; set; }
public string country { get; set; }
}
public class Customer
{
public List<Address> address { get; set; }
public List<Privacy> privacy { get; set; }
}
public class Privacy
{
public string username { get; set; }
public string password { get; set; }
}
public class Root
{
public Customer customer { get; set; }
}

我成功做到了:

string userName;
string pwd;
string cityName;
string countryName;
//Loop privacy
foreach (var customer_privacy in customer.privacy)
{
userName = customer_privacy.username;
pwd = customer_privacy.password;
}

// insert privacy
DbCommandInsertLeads.Parameters.AddWithValue("@username", (object)userName ?? DBNull.Value);
DbCommandInsertLeads.Parameters.AddWithValue("@password", (object)pwd ?? DBNull.Value);

//Loop address
foreach (var customer_address in customer.address)
{
countryName = customer_privacy.country;
cityName = customer_privacy.city;
}

// insert address
DbCommandInsertLeads.Parameters.AddWithValue("@country", (object)countryName ?? DBNull.Value);
DbCommandInsertLeads.Parameters.AddWithValue("@city", (object)cityName ?? DBNull.Value);   

最新更新