How to fill mongo Db table by C# Driver? - c#

I am not an expert of nosql but a year ago I created a mongodb table by using below code:
const string connectionString = "mongodb://localhost:27017";
// Create a MongoClient object by using the connection string
var client = new MongoClient(connectionString);
////Use the MongoClient to access the server
var database = client.GetDatabase("YUSUF");
////get mongodb collection
var collection = database.GetCollection("expressions");
var expression = new Expression { Id = Guid.NewGuid().ToString(),ExpressionSentence = "Test",Name = "yusuf",CreatedDate = DateTime.Now,Status = true };
collection.InsertOneAsync(expression);
public class Expression {
[BsonId]
public string Id { get; set; }
public string Name { get; set; }
public string ExpressionSentence { get; set; }
public bool Status { get; set; }
public DateTime CreatedDate { get; set; }
}
Today above codes is doing nothing now. Not working also not throwing any error. What am I doing wrong?

static void insert()
{
var connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);
var database = client.GetDatabase("YUSUF");
var collection = database.GetCollection<Expression>("expressions");
var expression = new Expression { Id = Guid.NewGuid().ToString(),ExpressionSentence = "Test",Name = "yusuf",CreatedDate = DateTime.Now,Status = true };
collection.InsertOneAsync(expression);
}
public class Expression {
[BsonId]
public string Id { get; set; }
public string Name { get; set; }
public string ExpressionSentence { get; set; }
public bool Status { get; set; }
public DateTime CreatedDate { get; set; }
}
have to work with the latest C# MongoDB Driver.
MY METHOD
static void insert()
{
var connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);
var database = client.GetDatabase("fairytale");
// var unicorns = database.GetCollection("unicorns");
var unicorns = database.GetCollection<BsonDocument>("unicorns");
int i = 0;
while (i < 5000)
{
var document = new BsonDocument
{
{"name",GenerateRandomUnicornName()},
{"horns",Random.Next(50)},
{"likes",new BsonArray{ "apple", "onion" }},
};
unicorns.InsertOneAsync(document);
i++;
}
}

Related

No members mapped for type - CSV Helper

I am new to using CSVHelper and AutoMapper and am getting the following error when trying to:
public async Task<IActionResult> OnPostAsync()
{
if (BolCsv != null)
{
try
{
using (var reader = new StreamReader(BolCsv.OpenReadStream()))
using (var csvr = new CsvReader(reader, System.Globalization.CultureInfo.CurrentCulture))
{
csvr.Configuration.Delimiter = "\t";
csvr.Configuration.HeaderValidated = null;
csvr.Configuration.MissingFieldFound = null;
var bolDtos = csvr.GetRecords<BOLDto>().ToList();
var bols = _mapper.Map<IEnumerable<BOL>>(bolDtos);
await _context.SaveChangesAsync();
return RedirectToPage("./Index");
}
}
var bolDtos = csvr.GetRecords<BOLDto>();
Error: No members are mapped for type 'BOLDto'.
BOLDto:
{
public class BOLDto
{
[Name("BOLNumber")]
public int BOLNumber { get; set; }
[Name("ProductID")]
public int ProductID { get; set; }
[Name("ProductDescription")]
public string ProductDescription { get; set; }
etc...
}
}
BOL.cs:
{
public class BOL
{
public int BOLNumber { get; set; }
public int ProductId { get; set; }
public string ProductDescription { get; set; }
etc...
}
}
As I mentioned Im new to ASP.Net Core AutoMapper, and CSVHelper... how do I solve this issue?
It looks like your BOLDto class has properties, but that error message is the same as I would get if the class had fields instead of properties. So you might want to try CsvHelper.Configuration.MemberTypes.Fields. Also that must be an older version of CsvHelper you are using, because that is not how you would need to set up the configuration in the current version. But it should still work for you to add csvr.Configuration.MemberTypes = CsvHelper.Configuration.MemberTypes.Fields.
void Main()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<BOLDto, BOL>());
var _mapper = config.CreateMapper();
var csvConfig = new CsvConfiguration(CultureInfo.InvariantCulture)
{
Delimiter = "\t",
HeaderValidated = null,
MissingFieldFound = null,
MemberTypes = CsvHelper.Configuration.MemberTypes.Fields
};
using (var reader = new StringReader("BOLNumber\tProductID\tProductDescription\t\n1\t2\tMy Product"))
using (var csvr = new CsvReader(reader, csvConfig))
{
var bolDtos = csvr.GetRecords<BOLDto>().ToList();
var bols = _mapper.Map<IEnumerable<BOL>>(bolDtos);
}
}
public class BOLDto
{
[Name("BOLNumber")]
public int BOLNumber;
[Name("ProductID")]
public int ProductID;
[Name("ProductDescription")]
public string ProductDescription;
}
public class BOL
{
public int BOLNumber { get; set; }
public int ProductId { get; set; }
public string ProductDescription { get; set; }
}

Error while reading data from azure table storage

I'm writing a code to read values from a table storage. The code is similar to printing nodes in a tree level by level.
eg:
root
Level1child1 -> Level1child2 -> Level1child3
string tablename = "<table-name">;
string storageAccountName = "<storage-account-name";
var baseurl = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var sastoken = getAccountSASToken();
string filter = #"&$filter=PartitionKey%20eq%20'123'%20and%20RowKey%20eq%20'abc'";
baseurl = $"{baseurl}{sastoken}{filter}";
var data = HttpHelper.GetForOData(baseurl);
var responseData = data.Data.Replace(".", "_");
var odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Queue<int> strQ = new Queue<int>();
Console.WriteLine(odata.value[0].Email);
strQ.Enqueue(odata.value[0].TreeNodeID);
while (strQ.Any())
{
var url = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var token = _tableStorageRepository.GetAccountSASToken();
filter = #"&$filter=ParentNodeId%20eq%20" + strQ.Peek();
url = $"{url}{token}{filter}";
data = HttpHelper.GetForOData(url);
responseData = data.Data.Replace(".", "_");
odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
foreach (var m in odata?.value)
{
Console.WriteLine(m.Email);
strQ.Enqueue(m.TreeNodeID);
}
strQ.Dequeue();
}
public class ODataResponse
{
public string odata_metadata { get; set; }
public List<ODatavalue> value { get; set; }
}
public class ODatavalue
{
public string odata_type { get; set; }
public string odata_id { get; set; }
public string odata_etag { get; set; }
public string odata_editLink { get; set; }
public string RowKey { get; set; }
public string Email { get; set; }
public int ParentNodeID { get; set; }
public int TreeNodeID { get; set; }
}
Code for HttpHelper class: https://github.com/xyz92/httphelper/blob/master/HttpHelper.cs
The first time when I ran this code, it only printed root node.
The second time when I ran this code, it printed root node and Level1child1 node.
For the next runs, it printed root node, Level1child1 node & Level1child2 node.
The last node Level1child3 node is getting printed very rarely on some runs.
What am I missing in this code?
UPDATE:
Sample responseData:
{
"odata_metadata": "https://<storage-account-name>_table_core_windows_net/$metadata#<table-name>",
"value": [{
"odata_type": "<storage-account-name>_<table-name>",
"odata_id": "https://<storage-account-name>_table_core_windows_net/<table-name>(PartitionKey='123',RowKey='abc')",
"odata_etag": "W/\"datetime'2020-09-01T16%3A34%3A21_3342187Z'\"",
"odata_editLink": "<table-name>(PartitionKey='123',RowKey='abc')",
"PartitionKey": "123",
"RowKey": "abc",
"Timestamp#odata_type": "Edm_DateTime",
"Timestamp": "2020-09-01T16:34:21_3342187Z",
"Email": "email",
"ParentNodeID": 1,
"TreeNodeID": 2
}
]
}
Table columns:
Sample data in Table:
Sample outputs while running code:
According to my test, I cannot reproduce your issue in my environment. My test is as below
Table columns:
Sample data in table
Code I use your HttpHelper class to send request
class Program
{
static async Task Main(string[] args)
{
string storageAccountName = "andyprivate" ;
string tableName = "test";
var baseurl = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var sastoken = "";
string filter = #"&$filter=PartitionKey%20eq%20'123'%20and%20RowKey%20eq%20'abc'";
baseurl = $"{baseurl}{sastoken}{filter}";
var data = HttpHelper.GetForOData(baseurl);
var responseData = data.Data.Replace(".", "_");
var odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Queue<int> strQ = new Queue<int>();
Console.WriteLine("----root----");
Console.WriteLine(odata.value[0].Email);
strQ.Enqueue(odata.value[0].TreeNodeID);
while (strQ.Any())
{
int i = 0;
var url = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var token = "";
filter = #$"&$filter=ParentNodeID eq {strQ.Peek()}";
url = $"{ url}{token}{filter}";
data = HttpHelper.GetForOData(url);
responseData = data.Data.Replace(".", "_");
odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Console.WriteLine($"----TreeNode{strQ.Peek()}----");
foreach (var m in odata?.value)
{
if (i == 0) {
strQ.Enqueue(m.TreeNodeID);
i = 1;
}
Console.WriteLine(m.Email);
}
strQ.Dequeue();
}
Console.ReadLine();
}
}
public class ODataResponse
{
public string odata_metadata { get; set; }
public List<ODatavalue> value { get; set; }
}
public class ODatavalue
{
public string odata_type { get; set; }
public string odata_id { get; set; }
public string odata_etag { get; set; }
public string odata_editLink { get; set; }
public string RowKey { get; set; }
public string Email { get; set; }
public int ParentNodeID { get; set; }
public int TreeNodeID { get; set; }
}
Update
My test code
Rest API (I use your HttpHelper class to send request)
class Program
{
static async Task Main(string[] args)
{
string storageAccountName = "andyprivate" ;
string tableName = "test";
var baseurl = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var sastoken = "";
string filter = #"&$filter=PartitionKey%20eq%20'123'%20and%20RowKey%20eq%20'abc'";
baseurl = $"{baseurl}{sastoken}{filter}";
var data = HttpHelper.GetForOData(baseurl);
var responseData = data.Data.Replace(".", "_");
var odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Queue<int> strQ = new Queue<int>();
Console.WriteLine("----root----");
Console.WriteLine(odata.value[0].Email);
strQ.Enqueue(odata.value[0].TreeNodeID);
while (strQ.Any())
{
int i = 0;
var url = #$"https://{storageAccountName}.table.core.windows.net/{tableName}()";
var token = "";
filter = #$"&$filter=ParentNodeID eq {strQ.Peek()}";
url = $"{ url}{token}{filter}";
data = HttpHelper.GetForOData(url);
responseData = data.Data.Replace(".", "_");
odata = JsonConvert.DeserializeObject<ODataResponse>(responseData);
Console.WriteLine($"----TreeNode{strQ.Peek()}----");
foreach (var m in odata?.value)
{
if (i == 0) {
strQ.Enqueue(m.TreeNodeID);
i = 1;
}
Console.WriteLine(m.Email);
}
strQ.Dequeue();
}
Console.ReadLine();
}
}
public class ODataResponse
{
public string odata_metadata { get; set; }
public List<ODatavalue> value { get; set; }
}
public class ODatavalue
{
public string odata_type { get; set; }
public string odata_id { get; set; }
public string odata_etag { get; set; }
public string odata_editLink { get; set; }
public string RowKey { get; set; }
public string Email { get; set; }
public int ParentNodeID { get; set; }
public int TreeNodeID { get; set; }
}
SDK. I use the package Microsoft.Azure.Cosmos.Table
string storageAccountName = "andyprivate";
string accountKey ="";
string tableName = "test";
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(storageAccountName, accountKey), true);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
CloudTable table = tableClient.GetTableReference(tableName);
TableOperation retrieveOperation = TableOperation.Retrieve<CustomEntity>("123", "abc");
TableResult result = await table.ExecuteAsync(retrieveOperation);
CustomEntity entity = result.Result as CustomEntity;
Queue<int> strQ = new Queue<int>();
Console.WriteLine("----root----");
Console.WriteLine(entity.Email);
strQ.Enqueue(entity.TreeNodeID);
while (strQ.Any()) {
int i = 0;
TableQuery<CustomEntity> query = new TableQuery<CustomEntity>()
.Where(
TableQuery.GenerateFilterConditionForInt("ParentNodeID", QueryComparisons.Equal,strQ.Peek())
);
Console.WriteLine($"----TreeNode{strQ.Peek()}----");
foreach (CustomEntity m in table.ExecuteQuery(query) ) {
Console.WriteLine(m.Email);
if (i == 0) {
strQ.Enqueue(m.TreeNodeID);
i = 1;
}
}
strQ.Dequeue();
}

How to push to do a emdeded document in mongodb c# driver

i have a problem how to push a document into a another document to create a embeded document in c#.
my models look like :
public class ModelKnjiga
{
public ModelKnjiga() { }
[BsonId(IdGenerator = typeof(CombGuidGenerator))] // pojavljuje se greška kod BSON tipa podataka kod ID-a,preuzoteo s dokumentacije drivera 1.5
public Guid Id { get; set; }
[BsonElement("naziv")]
public string naziv { get; set; }
[BsonElement("autor")]
public string autor { get; set; }
[BsonElement("godina_izdanja")]
public string godina_izdanja { get; set; }
[BsonElement("izdavac")]
public string izdavac { get; set; }
[BsonElement("ocjena")]
public String ocjena { get; set; }
[BsonElement("čitam")]
public Boolean čitam { get; set; }
[BsonElement("završio")]
public Boolean završio { get; set; }
}
another model looks like :
public ModelKorisici () {
KnjigaLista = new List<ModelKnjiga>();
}
[BsonId] // pojavljuje se greška kod BSON tipa podataka kod ID-a,preuzoteo s dokumentacije drivera 1.5 CombGuidGenerator
public Guid Identifikator { get; set; }
[BsonElement("ime")]
public string ime { get; set; }
[BsonElement("prezime")]
public string prezime { get; set; }
[BsonElement("lozinka")]
public string lozinka { get; set; }
[BsonElement("email")]
public string email { get; set; }
[BsonElement("kor_ime")]
public string kor_ime { get; set; }
[BsonElement("uloga")]
public string uloga { get; set; }
public List<ModelKnjiga> KnjigaLista { get; set; }
}
and now i am tring to push a modelKnjiga into a modelKorisici
I am trying with this method...
public void dodajKnjiguKorisniku(ModelKnjiga knjiga, Guid id)
{
MongoCollection<ModelKorisici> korisniciKolekcija = GetTasksCollectionKlijenti();
try
{
var pronadiKorisnika = Query<ModelKorisici>.EQ(e => e.Identifikator, id);
var PushPodataka = Update<ModelKorisici>.Push(e => e.KnjigaLista, knjiga);
korisniciKolekcija.Update(pronadiKorisnika, PushPodataka);
}
catch (MongoCommandException ex)
{
string msg = ex.Message;
}
}
In robomongo, the object KnjigaLista is always Null...
Can somebody help?
I think Update is legacy.
(in your models you don't have to use strings only. Eg.: godina_izdanja could be DateTime(), and ocjena some numeric format...)
I made an (async) example with your models, hope it helps:
class Program
{
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
Console.WriteLine("");
Console.WriteLine("press enter");
Console.ReadKey();
}
static async Task MainAsync(string[] args)
{
ModelKnjiga knga = new ModelKnjiga()
{
autor = "Author",
godina_izdanja = "2015",
izdavac = "izdavac",
naziv = "naziv",
ocjena = "20",
završio = true,
čitam = true
};
ModelKnjiga knga2 = new ModelKnjiga()
{
autor = "Author2",
godina_izdanja = "2016",
izdavac = "izdavac2",
naziv = "naziv2",
ocjena = "202",
završio = false,
čitam = false
};
ModelKnjiga knga3 = new ModelKnjiga()
{
autor = "Author3",
godina_izdanja = "2017",
izdavac = "izdavac3",
naziv = "naziv3",
ocjena = "203",
završio = false,
čitam = true
};
ModelKorisici mcor = new ModelKorisici()
{
email = "no#where.com",
ime = "ime",
KnjigaLista = new List<ModelKnjiga>() { knga, knga2 },
kor_ime = "kor_ime",
uloga = "uloga",
lozinka = "lozinka",
prezime = "prezime"
};
var client = new MongoClient();
var db = client.GetDatabase("KnjigaDB");
var korisici = db.GetCollection<ModelKorisici>("Korisici");
//After first run comment this line out
await korisici.InsertOneAsync(mcor);
//After first run UNcomment these lines
//var filter = Builders<ModelKorisici>.Filter.Eq("email", "no#where.com");
//var update = Builders<ModelKorisici>.Update.Push("KnjigaLista", knga3);
//await korisici.UpdateOneAsync(filter, update);
}
}
if you don't like async, change the last line with this:
korisici.UpdateOne(filter, update);

Entity Framework - Conditionally include related entities

I maintain an API that, based on a request for a list of people, returns a different result set based on the request. For example, some API clients want to get a list of people and a list of their interactions, others want people and a list of their metadata. All this can be specified int he request to the API method that returns people.
This does not appear to work:
using (var dbcontext = new ExampleEntities())
{
var query = dbcontext.People.AsQueryable();
//determined in earlier application logic based on request
if(includeMetadata)
{
query = query.Include("metadata");
}
//determined in earlier application logic based on request
if(includeInteractions)
{
query = query.Include("interactions");
}
/* ...SNIP... */
}
What I don't want to do is this:
var query = dbcontext.People.Include("Metadata").Include("interactions");
which will mean every request to get a person will include ALL their related entities, even if the requesting API client does not need them.
I also don't want to code every possible combination of logic:
if(includeMetadata && includeInteractions)
{
var query = dbcontext.People.Include("Metadata").Include("interactions");
}
else if(includeMetadata)
{
var query = dbcontext.People.Include("Metadata");
}
else if(includeInteractions)
{
var query = dbcontext.People.Include("Interactions");
}
else
{
var query = dbcontext.People;
}
This will result in hard-to-maintain code, however, I realize I could code generate this if needed.
You can chain the IQueryable's
using (var dbcontext = new ExampleEntities())
{
var query = dbcontext.People.AsQueryable();
if(includeMetadata)
{
query = query.Include("metadata");
}
if(includeInteractions)
{
query = query.Include("interactions");
}
}
Your first example should work if you replace u with query
u = u.Include("metadata");
with
query = query.Include("metadata");
Works fine here... checking the sql statements with the EF 6 Log handler
[TestClass]
public void SomeTestClass
{
[TestMethod]
public void ShouldLoadOnlyRequiredCollections()
{
Database.SetInitializer(new DropCreateDatabaseAlways<HomesContext>());
var db = new HomesContext();
Assert.IsFalse(db.Homes.Any());
var home = db.Homes.Create();
db.Homes.Add(home);
home.Staff.Add(new Staff { Name = "wilma" });
home.Staff.Add(new Staff { Name = "betty" });
home.Residents.Add(new Resident { Name = "fred" });
home.Residents.Add(new Resident { Name = "barney" });
db.SaveChanges();
db = null;
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<HomesContext>());
var sb = new StringBuilder();
db = new HomesContext();
db.Database.Log = ((s) => { sb.Append(s + "\r"); });
Assert.IsTrue(db.Homes.Any());
string log;
log = sb.ToString();
Assert.IsTrue(sb.ToString().Contains("FROM [dbo].[Homes]"));
sb = new StringBuilder(); //ok get residents
var q = db.Homes.Include("Residents");
Assert.IsTrue(string.IsNullOrEmpty(sb.ToString()));
var lst = q.ToList();
log = sb.ToString();
Assert.IsTrue(sb.ToString().Contains("[dbo].[Homes]"));
Assert.IsTrue(sb.ToString().Contains("[dbo].[Residents]"));
Assert.IsTrue(!sb.ToString().Contains("[dbo].[Staff]"));
sb = new StringBuilder(); //get staff
q = db.Homes.Include("Staff");
Assert.IsTrue(string.IsNullOrEmpty(sb.ToString()));
lst = q.ToList();
log = sb.ToString();
Assert.IsTrue(log.Contains("[dbo].[Homes]"));
Assert.IsTrue(!log.Contains("[dbo].[Residents]"));
Assert.IsTrue(log.Contains("[dbo].[Staffs"));
sb = new StringBuilder(); //get residents and staff
q = db.Homes.Include("Staff");
q = q.Include("Residents");
lst = q.ToList();
log = sb.ToString();
Assert.IsTrue(log.Contains("[dbo].[Homes]"));
Assert.IsTrue(log.Contains("[dbo].[Residents]"));
Assert.IsTrue(log.Contains("[dbo].[Staffs]"));
}
}
public class HomesContext:DbContext
{
public DbSet<Home> Homes { get; set; }
}
public class Home
{
public Home()
{
Staff = new List<Staff>();
Residents = new List<Resident>();
}
public int HomeId { get; set; }
public string HomeName { get; set; }
public int MaxResidents { get; set; }
public int MaxStaff { get; set; }
public int CurrentResidents { get; set; }
[NotMapped]
public int CurrentStaff { get; set; }
public IList<Staff> Staff { get; set; }
public IList<Resident> Residents { get; set; }
}
public class Staff
{
public int StaffId { get; set; }
public string Name { get; set; }
public int HomeId { get; set; }
public Home Home { get; set; }
}
public class Resident
{
public int ResidentId { get; set; }
public string Name { get; set; }
public int HomeId { get; set; }
public Home Home { get; set; }
}

c# List adding items using For loop

I have a problem with c# List, not sure where I'm missing the point while adding a new object to the Managepagesid List!
public class Clients
{
[BsonId]
public string Id { get; set; } //Object ID managed by MongoDb
public string Name { get; set; } //Client Name
public string Phone { get; set; } //Client Phone
public string Email { get; set; } //Client E-mail
public string Username { get; set; } //Client Username
public DateTime LastModified { get; set; } //Client Last Login
public string FB_User_Id { get; set; } //Client FB User ID
public AccessToken UserAccessToken { get; set; } //AccessToken which is stored while user is logged in.
public List<ManagePages> Manage_Pages_id { get; set; } //The pages maintained by the specific client
}
I'm trying to access add a new item into ManagePage_id list but its thrwing some null exception.. Help!
Clients client = new Clients();
client.FB_User_Id = FBData.id;
client.Name = FBData.name;
client.Email = FBData.email;
client.Username = FBData.username;
for (int index = 0; index < FBData.accounts["data"].Count; index++)
{
ManagePages pagedetails = new ManagePages()
{
page_id = FBData.accounts["data"][index].id,
page_name = FBData.accounts["data"][index].name,
ManagePages_AccessTokens = new AccessToken()
{
AccessToken_accessToken = FBData.accounts["data"][index].access_token,
AccessToken_expiryDate = DateTime.Now
},
ManagePages_category = FBData.accounts["data"][index].category
};
var category = pagedetails.ManagePages_category;
client.Manage_Pages_id.Add(pagedetails);
}
Stack Trace added!
Exception>System.NullReferenceExceptionObject reference not set to an instance of an object. at Vega_MongoDB.FBDataAccess.ClientFBRepository.ClientsData(String accessToken) in g:\Development\Vega_MongoDB\Vega_MongoDB\FBDataAccess\ClientFBRepository.cs:line 48
at Vega_MongoDB.Models.ClientRepository..ctor(String connection) in g:\Development\Vega_MongoDB\Vega_MongoDB\Models\Clients\ClientRepository.cs:line 47
at Vega_MongoDB.Models.ClientRepository..ctor() in g:\Development\Vega_MongoDB\Vega_MongoDB\Models\Clients\ClientRepository.cs:line 23
at Vega_MongoDB.Controllers.ClientsController..cctor() in g:\Development\Vega_MongoDB\Vega_MongoDB\Controllers\ClientsController.cs:line 18
And I have checked the pagedetails object, it contains all the data..
Thanks
Vishnu
You should create an instance of the list before adding item:
client.Manage_Pages_id = new List<ManagePages>();
for (int index = 0; index < FBData.accounts["data"].Count; index++)
{
ManagePages pagedetails = new ManagePages()
{
page_id = FBData.accounts["data"][index].id,
page_name = FBData.accounts["data"][index].name,
ManagePages_AccessTokens = new AccessToken()
{
AccessToken_accessToken = FBData.accounts["data"][index].access_token,
AccessToken_expiryDate = DateTime.Now
},
ManagePages_category = FBData.accounts["data"][index].category
};
var category = pagedetails.ManagePages_category;
client.Manage_Pages_id.Add(pagedetails);
}
Try adding this to your class:
public Clients()
{
this.Manage_Pages_id = new List<ManagePages>();
}
You need to initialize your list before adding anything to it. You can do this in the constructor for the Clients class or in your calling code (as Artem suggested).
public class Clients
{
//properties
public Clients()
{
Manage_Pages_id = new List<ManagePages>();
}
}

Categories