1

i use entity framework and have the below code:

public class AdvPackageInfo
{
    private int PackageId;
    private string Caption;
    private int Duration;
    private int Count;
    private bool Enable;
    private float Price;
}


 AdvertismentAgancyEntities enn = new AdvertismentAgancyEntities();

 List<AdvPackageInfo> lst = (from s in enn.Tbl_AdvPackage select new AdvPackageInfo { }).ToList();

    repeater1.DataSource = lst;
    repeater1.DataBind();

but it works just 1 time and when my page load for the second time it fails in execution and raise NullReferenceException...!!

according to this pag : http://connect.microsoft.com/VisualStudio/feedback/details/663200/linq-to-entities-throws-nullreferenceexception-when-the-output-attribute-set-is-empty
it's dot net framework problem.

i try this code too :

var q = (from s in enn.AdvPackage select s).toList();

but it doesn't work either.

is there any better way to make a linq select to a list????

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
maryam mohammadi
  • 694
  • 3
  • 14
  • 27

1 Answers1

3

Instead of this line:

List<AdvPackageInfo> lst = 
    (from s in enn.Tbl_AdvPackage select new AdvPackageInfo { }).ToList();

You could do this:

var lst = new List<AdvPackageInfo>();
for (int i = 0; i < enn.Tbl_AdvPackage.Count(); i++)
    lst.Add(new AdvPackageInfo());

(Note that the suggested workaround in the MS Connect page is wrong. Using Enumerable.Repeat will create a list full of references to a single object)


Update per comment below: If you're just trying to load the datagrid, then you just need to retrieve the list as:

var lst = enn.Tbl_AdvPackage.ToList();
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
  • thank u. it works for the error but there is another problem now! it returns empty records. i mean although there is 5 records of data it returns 5 empty records. i see 5 empty records in grid!! – maryam mohammadi Jan 19 '13 at 11:47
  • Then you haven't stated what you're trying to do very clearly. You're actually trying to just load the records, not create an empty object object for each record. Please see the update. – Eren Ersönmez Jan 19 '13 at 12:07