Search code examples
c#asp.net-mvcstrongly-typed-dataset

ASP.NET Controller with DataRow


I'm building a simple ASP.NET application that communicates with a SQL server database. In a separate project, I have the dataset that was generated by Visual Studio. I'm trying to expose an API that will display all users in the database, but I'm getting an exception.

Here is the code:

public class UserController : ApiController {

    public IEnumerable<GWDataSet.usersRow> GetAllUsers() {
        GWDataSet gw = new GWDataSet();
        usersTableAdapter adapter = new usersTableAdapter();
        adapter.Fill(gw.users);

        return gw.users.AsEnumerable();
    }
}

And this is the exception:

Type 'System.Data.DataRow' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.

Is there a way around this, other than to manually edit the system-generated code? My fear is that next time I make a change to the dataset, it will overwrite all the datacontract elements I add in. I would think there's a way to do this, but I can't seem to find it.

Thanks!


Solution

  • It is because you cannot share DataRow objects. They are not serializable. If you want to share it, you should create DTO objects. It is a good pratice of shareing objects from services, APIs, etc. Tru to convert your DataRow to a DTO object. Try something like:

    Create your class to be this DTO, for sample:

    [Serializable]
    public class UserDTO
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string Birthday { get; set; }
        /* other properties you need */
    }
    

    And in your web api, try this:

    public class UserController : ApiController {
    
        public IEnumerable<UserDTO> GetAllUsers() {
            GWDataSet gw = new GWDataSet();
            usersTableAdapter adapter = new usersTableAdapter();
            adapter.Fill(gw.users);
    
            List<UserDTO> list = new List<UserDTO>();
    
            foreach(DataRow row in gw.users.Rows) 
            {
                UserDTO user = new UserDTO();
                user.FirstName = row["Name"].ToString();
                // fill properties
    
               list.Add(user);
            }
    
            return list;
        }
    }