How to return anonymous type from c# method that uses LINQ to SQL
Make the anonymous type into a class...
public class Person
{
public Person() {
}
public String Name { get; set; }
public DateTime DOB { get; set; }
}
Person p =
from person in db.People
where person.Id = 1
select new Person {
Name = person.Name,
DOB = person.DateOfBirth
}
how to return an anonymous type in linq-to-sql
Here's a blog post on naming anonymous types in .NET using VS 2010's Generate From Usage functionality.
http://diditwith.net/2009/10/24/NamingAnonymousTypesWithGenerateFromUsage.aspx
Return anonymous type results?
I tend to go for this pattern:
public class DogWithBreed
{
public Dog Dog { get; set; }
public string BreedName { get; set; }
}
public IQueryable<DogWithBreed> GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new DogWithBreed()
{
Dog = d,
BreedName = b.BreedName
};
return result;
}
It means you have an extra class, but it's quick and easy to code, easily extensible, reusable and type-safe.
How to Convert Anonymous Type to List dynamic using Linq to SQL in C#
You can use strongly return type for your method like List<ClassName>
instead of List<dynamic>
public List<ClassName> GetScanAudit(object Id, DateTime? fromTime, DateTime? toTime, string type = null, string user = null, Pager pager = null)
{
...
}
Then your query will be
var data = query.Select(x =>
new ClassName
{
TypeFullName = x.audit.TypeFullName,
UserName = x.audit.UserName,
EventType = x.audit.EventType,
EventDateUTC = x.audit.EventDateUTC,
LogDetails = x.audit.LogDetails.ToList(),
Name = x.entaudits.Name,
Description = x.entaudits.Description
})
.OrderByDescending(x => x.EventDateUTC)
.Skip(pager.From)
.Take(pager.PageSize);
var list = data.ToList<ClassName>();
And your strongly type class look like
public class ClassName
{
public string TypeFullName { get; set; }
public string UserName { get; set; }
public string EventType { get; set; }
public DateTime EventDateUTC { get; set; }
public List<LogDetail> LogDetails { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Make sure the datatype of each property should match in your .Select
clause in query
Edit:
if (pager != null)
{
var totalRecords = query.Count();
pager.TotalRecords = totalRecords;
var data = query.Select(x =>
new AuditInfo
{
TypeFullName = x.audit.TypeFullName,
UserName = x.audit.UserName,
EventType = x.audit.EventType,
EventDateUTC = x.audit.EventDateUTC,
LogDetails = x.audit.LogDetails.ToList(),
Name = x.entaudits.Name,
Description = x.entaudits.Description
})
.OrderByDescending(x => x.EventDateUTC)
.Skip(pager.From)
.Take(pager.PageSize);
try
{
var list1 = data.ToList<AuditInfo>();
}
catch (Exception e)
{
}
var list = data.ToList<AuditInfo>();
pager.RecordCount = list.Count;
return list;
}
else
{
var list = query.Select(x =>
new AuditInfo
{
TypeFullName = x.audit.TypeFullName,
UserName = x.audit.UserName,
EventType = x.audit.EventType,
EventDateUTC = x.audit.EventDateUTC,
LogDetails = x.audit.LogDetails.ToList(),
Name = x.entaudits.Name,
Description = x.entaudits.Description
})
.OrderByDescending(x => x.EventDateUTC)
.ToList<AuditInfo>();
return list;
}
How to return anonymous type from EF sql query
It appears that EF doesn't support returning any types other than ones that have EF mappings when using the ObjectContext.ExecuteStoreQuery() method.
I ended up using a SqlCommand object and datareader with an anonymous type.
Using Anonymous Type from LINQ to SQL
I'm not saying you should do this, on the contrary, but you can use dynamics to return anonymous types and address their properties later:
public IEnumerable<dynamic> GetReferenceList()
{
return from r in entity.Reference
join d in entity.Reference_Detail on r.id equals d.refid
select new { ID = d.id, REFNAME = r.Name, DETAIL = d.Name };
}
And in consuming code:
var data = GetReferenceList();
foreach (var item in data)
{
var name = (string)(item.REFNAME);
...
}
You'll soon start to hate this approach. You'll keep casting the dynamic types to runtime types, you won't have intellisense (on item.
in this case), you won't have compile-time checking, so it's error-prone and susceptible to all kinds of subtle bugs. Do yourself a favor and use named types.
Use anonymous type for LINQ based lists instead of var
If you want to use a tuple type (that's what your (string col1, string col2)
is) instead of an anonymous type (that's what your new { col1=x.col1...}
is), you need another syntax:
List<(string col1, string col2)> list = context.Table1
.Select( // linq to entities
x => new
{
col1 = x.col1,
col2 = x.col2
})
.ToArray() // go on with linq to objects for use of tuple types
.Select(x => (col1: x.col1, col2: x.col2))
.ToList();
ValueTuples aren't supported in Expression trees, so you might need to use a combination of anonymous types and tuple types in your query
See Tuple types,
Choosing between anonymous and tuple types
Related Topics
Databindings Don't Seem to Refresh
Retrieve Image from Database in ASP.NET
How to Use Microsoft.Office.Interop.Excel on a MAChine Without Installed Ms Office
How to Override an Existing Extension Method
Creating Dynamic Queries with Entity Framework
Password Masking Console Application
Very Slow Compile Times on Visual Studio 2005
404 Error After Adding Web API to an Existing MVC Web Application
How to Compare Only Date Without Time in Datetime Types in Linq to SQL with Entity Framework
Does Entity Framework Code First Support Stored Procedures
What's the New C# Await Feature Do
Appsettings Get Value from .Config File
Why Is Inserting Entities in Ef 4.1 So Slow Compared to Objectcontext
Verifying That a String Contains Only Letters in C#