Initialization Expression
This article is relevant to entity models that utilize the deprecated Visual Studio integration of Telerik Data Access. The current documentation of the Data Access framework is available here.
An initialization expression initializes a new object. The following types can be initialized and returned by a LINQ query:
- A collection of zero or more typed objects or a projection of complex types in the domain model.
- CLR types.
- Anonymous types.
An anonymous type initialization is shown in the following example in query expression syntax:
using ( EntitiesModel dbContext = new EntitiesModel() )
{
var query = from product in dbContext.Products
where product.UnitPrice > 30
select new
{
Name = product.ProductName,
Price = product.UnitPrice
};
foreach ( var item in query )
{
Console.WriteLine( "Name: {0}, Price: {1}", item.Name, item.Price );
}
}
Using dbContext As New EntitiesModel()
Dim query = From product In dbContext.Products
Where product.UnitPrice > 30
Select New With {Key .Name = product.ProductName, Key .Price = product.UnitPrice}
For Each item In query
Console.WriteLine("Name: {0}, Price: {1}", item.Name, item.Price)
Next item
End Using
The following example in method-based query syntax shows anonymous type initialization:
using ( EntitiesModel dbContext = new EntitiesModel() )
{
var query = dbContext.Products.Where( p => p.UnitPrice > 30 ).Select(
p => new
{
Name = p.ProductName,
Price = p.UnitPrice
} );
foreach ( var item in query )
{
Console.WriteLine( "Name: {0}, Price: {1}", item.Name, item.Price );
}
}
Using dbContext As New EntitiesModel()
Dim query = dbContext.Products.Where(Function(p) p.UnitPrice > 30).Select(Function(p) _
New With _
{ _
Key .Name = p.ProductName, _
Key .Price = p.UnitPrice _
})
For Each item In query
Console.WriteLine("Name: {0}, Price: {1}", item.Name, item.Price)
Next item
End Using
User-defined class initialization is also supported. The following example in query expression syntax shows a custom class being initialized in the query:
public class MyProduct
{
public string Name
{
get;
set;
}
public decimal Price
{
get;
set;
}
}
Public Class MyProduct
Public Property Name() As String
Public Property Price() As Decimal
End Class
using ( EntitiesModel dbContext = new EntitiesModel() )
{
var query = dbContext.Products.Where( p => p.UnitPrice > 30 ).Select(
p => new MyProduct
{
Name = p.ProductName,
Price = p.UnitPrice
} );
foreach ( var item in query )
{
Console.WriteLine( "Name: {0}, Price: {1}", item.Name, item.Price );
}
}
Using dbContext As New EntitiesModel()
Dim query = dbContext.Products.Where(Function(p) p.UnitPrice > 30).Select(Function(p) _
New MyProduct With _
{ _
.Name = p.ProductName, _
.Price = p.UnitPrice _
})
For Each item In query
Console.WriteLine("Name: {0}, Price: {1}", item.Name, item.Price)
Next item
End Using