0

In most cases, I use a simple observable collection in C# and fill it with data fetched from a SQL query.

Something like this works:

public class MyClass
{
    public string mystring1 { get; set; } = String.Empty;
    public string mystring1 { get; set; } = String.Empty;
}

ObservableCollection<MyClass> MyClassData = new ObservableCollection<MyClass>();

I can easily insert data fetched by SqlDataReader:

while (dataReader.Read())
{
    MyClassData.Add(new MyClass{ mystring1 = dataReader.GetValue(0).ToString(), mystring2 =  dataReader.GetValue(1).ToString() }});
}

As it turned out, I need a 3rd member in my class and it should be not a simple string but a list, so I wrote this:

public class MySubClass
{
    public string mystring3 { get; set; }
}

public class MyClass
{
    public string mystring1 { get; set; } = String.Empty;
    public string mystring1 { get; set; } = String.Empty;
    public List<MySubClass> MySubClassData { get; set; }
}

Even its only a simple string in MySubClass, I need this as list for later use.

And now I have the big problem to find the right syntax how to get the SQL data into the new structure and all I get is a bunch of curious errors while compiling.

I just don't know how to address the mystring3 in mySubClass as member of MyClass to store data in it.

Please give me a hint.

Thanks,

Hans

3
  • "all i get is a bunch of curious errorlines while compiling." - and were there some messages to go with that? perhaps about nulls? public List<MySubClass> MySubClassData { get; } = []; might solve most of that (which means the list is a get-only property, initialized to an empty list). Without knowing the structure of your query, it is hard to advise on how to populate that list - because it is no longer necessarily strictly 1:1 rows to objects Commented Jan 30 at 15:48
  • One way is to execute two queries and fill lists manually (usually it is fastet way). Other way is to LEFT JOIN to table with mystring3, return everything in one query and then on client side deduplicate records and fill collections. Currently it is effectively done by EF Core and linq2db, otherwise you have to do that manually. If you use Dapper here is the sample Commented Jan 30 at 16:09
  • Please show what error messages you're getting Commented Jan 30 at 16:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.