0

In the code below, I am converting the results of an SQL View to a DataTable:

DataTable tierOnes = db.xxxxxxxxx_vw_TierOnes.ToDataTable();

The View is defined in a separate class:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace DPN.Entities.Moonboot
{
    [Table("vw_TierOnes", Schema = "xxxxxxxxx")]
    public class xxxxxxxxx_vw_TierOnes
    {
        [Key]
        public Guid TierOneID { get; set; }
        public string TierOneName { get; set; }
        public DateTime DateCreated { get; set; }
        public Boolean IsActive { get; set; }
        public int? CreatedByUserID { get; set; }
    }
}

I try to retrieve data from columns AS BELOW:

foreach (DataRow row in tierOnes.Rows)
{
    if (row["IsActive"].ToString() == "True")
    {
        TierOne t1 = new TierOne();
        t1.Id = Guid.Parse(row["TierOneID"].ToString());
        t1.Name = row["TierOneName"].ToString();
        output.TierOnes.Add(t1);
    }
}

I get the following error:

Column 'TierOneID' does not belong to table .

Where did my column go? More importantly, how do I get this data?

default locale
  • 13,035
  • 13
  • 56
  • 62
Steve Staple
  • 2,983
  • 9
  • 38
  • 73
  • I wonder, how many columns are there in `tierOnes.Columns`? And which columns didn't make it? – default locale May 19 '17 at 13:27
  • Just the column I am asking about didn't make it. There are only 4 columns. Should be 5. – Steve Staple May 19 '17 at 13:28
  • If you execute the query separately from your program does it return the column? – Sam Marion May 19 '17 at 13:30
  • If i execute the query in SQL, yes, it returns all the columns. – Steve Staple May 19 '17 at 13:31
  • Is the column type in SQL Uniqueidentifier? – Sam Marion May 19 '17 at 13:33
  • It is indeed a uniqueidentifier – Steve Staple May 19 '17 at 13:37
  • 1
    Can you show the code for the ToDataTable extension method? – Henry Lu May 19 '17 at 13:37
  • Thanks Henry Lu - it did not occur to me that ToDataTable would be a custom method!! Is there a way to make sure it uses the proper method? – Steve Staple May 19 '17 at 13:51
  • 1
    Hi, as far as I know, there's nothing built into the framework to convert a EF dbset into a DataTable. You can use a custom extension method using reflection to determine the properties just as this post suggests http://stackoverflow.com/questions/27738238/convert-dbcontext-to-datatable-in-code-first-entity-framework or perhaps a simpler method would be to fall back to ADO.net and use the DataAdapter's Fill method to fill a DataSet's DataTables – Henry Lu May 19 '17 at 14:00

0 Answers0