在使用bindingSource3.AddNew()时,无法在'<> f__AnonymousType1`2上调用AddNew;

时间:2013-04-14 19:16:37

标签: c# linq entity-framework

当我使用以下代码时,会发生错误

testtelContext db = new testtelContext();
        var qry = (from p in db.firstlasts
                              join i in db.firstnames
                                  on p.Idfname equals i.Idfname
                              select new 
                              {
                                  id = p.idfl,
                                  name = i.fname

                              }).ToList();
        bindingSource3.DataSource = qry;

        dataGridView5.DataSource = bindingSource3;
        bindingSource3.AddNew(); 

使用bindingSource3.AddNew();

中的错误

错误:无法在'&lt;&gt; f__AnonymousType1 2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' type. This type does not have a public default constructor. You can call AddNew on the '<>f__AnonymousType1 2 [[System.Int32,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089],[System.String]上调用AddNew ,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]'type,如果设置AllowNew = true并处理AddingNew事件。

1 个答案:

答案 0 :(得分:1)

AddNew是匿名类型对象的集合时,您无法调用DataSource

所以你必须声明你的自定义类:

public class BindingItem
{
    public int id { get; set;}
    public string name { get; set; }
}

并更改您的查询以返回该对象的集合而不是匿名对象:

var qry = (from p in db.firstlasts
           join i in db.firstnames on p.Idfname equals i.Idfname
           select new BindingItem 
           {
               id = p.idfl,
               name = i.fname
           }).ToList();