Search code examples
c#sql-serverlistclassuser-defined

How to fill a custom typed List<> from SQL Server


I have a class named Author.cs defined as:

public class Author : Interfaces.INode
{
    private List<INode> _targetList;
    private List<IAttribute> _attributeObject;

    // Author class Constructor
    public Author()
    {
        _targetList = new List<INode>();
    }
    //implementazion of _TargetObject INode method
    public List<INode> _TargetObject
    {
        get
        {
             return _targetList;
        }
    }
    //implementazion of _AttributeObject INode method
    public List<IAttribute> _AttributeObject
    {
        get
        {
             return _attributeObject;
        }
    }

    public int _aID { get; set; }
    public string _aName { get; set; }  
    // 'CoAuthor', 'Venue' and 'Paper' are classes that  
    // implements an interface i.e. `IAttribute`
    public List<CoAuthor> _aCoAuthors { get; set; } 
    public List<Venue> _aVenue { get; set; }
    public List<Paper> _aPapers { get; set; }
    public string _aArea { get; set; }
}  

which implements an interface in Interfaces folder named Interfaces.INode.cs defined as:

public interface INode
{
    List<INode> _TargetObject { get; }
    List<IAttribute> _AttributeObject { get; }
}

public interface IAttribute : INode
{}  

Now I want to fill a list i.e. List<Author> i.e. is in another class named AuthorCollector.cs

List<Author> _eAthors = new List<Author>();  

I have tried as:

try
{
    SqlCommand _myCommand_1 = _con.CreateCommand();
    _myCommand_1.CommandText = @"SELECT Author_ID FROM M_DataFull  
                                 ORDER BY Author_ID, Year";
    var _AuthID = 0;
    int _Row_Counter = 0;

    using (SqlDataReader _myReader_1 = _myCommand_1.ExecuteReader())
    {
        while (_myReader_1.Read())
        {
            _Row_Counter++;
            _eAthors.Add(Convert.ToInt32(_myReader_1["Author_ID"]));
        }
        _myReader_1.Close();
     }
}
catch(Exception e)
{
     Console.WriteLine(e.Message);
}  

The error is:

The best overloaded method match for _eAuthors.Add() has some invalid arguments.


Solution

  • using (SqlDataReader _myReader_1 = _myCommand_1.ExecuteReader())
    {
        while (_myReader_1.Read())
        {
           _Row_Counter++;
           Author author = new Author();
           author._aId = Convert.ToInt32(_myReader_1["Author_ID"]);
           author._aName = Convert.ToString(_myReader_1["Author_Name"]);
           //etc...
           _eAthors.Add(author);
        }
        _myReader_1.Close();
    }