I have a linq query that populates the GridView
on Page_Load
. I have made a for
loop of Characters for the alphabet. In the .Command
of the LinkButton
that populates the LinkButton
, I am running a very similar query using the same parameters in the query and getting the below error.
The type '<>f__AnonymousType2' exists in both 'ConcernContracts.dll' and 'System.Web.WebPages.Deployment.dll'
void lnkCharacter_Command(object sender, CommandEventArgs e)
{
try
{
var lbtn = (LinkButton)lbl_Alphabet.FindControl("lnkCharacter" + e.CommandArgument);
var id = lbtn.Text;
using (var db = new dbDataContext())
{
var query = from n in db.tbl_Providers
where ((n.provider_Name.StartsWith(id)) && (n.provider_Deleted == false))
select new
{
n.ProviderId,
n.provider_Name
};
grd_Provider.DataSource = null;
grd_Provider.DataSource = query;
grd_Provider.DataBind();
}
}
catch (SystemException ex) { }
}
The LoadGrid() is the same, but it doesn't use the .StartsWith()
condition.
Do you have any Ideas how to solve the error?
The error doesn't throw an exception, but it doesn't populate the grid for either of the queries. The error was discovered in the following line: grd_Provider.DataSource = query;
From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.
Essentially an anonymous type is a reference type and can be defined using the var keyword. You can have one or more properties in an anonymous type but all of them are read-only. In contrast to a C# class, an anonymous type cannot have a field or a method — it can only have properties.
What Are Anonymous Types in C#? Anonymous types are class-level reference types that don't have a name. They allow us to instantiate an object without explicitly defining a type. They contain one or more read-only properties. The compiler determines the type of the properties based on the assigned values.
You are allowed to use an anonymous type in LINQ. In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.
Change your grid data source
grd_Provider.DataSource = query.ToList();
grd_Provider.DataBind();
or create List having two properties Provider Id and Name and bind that list from output like this.
List<Entities> abc=query.ToList();
grd_Provider.DataSource =abc;
grd_Provider.DataBind();
Here is a suggestion:
Your two similar queries are probably overlapping on that anonymous type you are selecting in the LINQ query. On one and only one of the queries, change the select new to look like this:
select new
{
Id = n.ProviderId,
Name = n.provider_Name
};
If you do this, the anonymous types shouldn't conflict anymore, since the one you don't modify will use the default names.
Good luck, and I hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With