5

I'm new to C# and Linq.

Actually, I want to return anonymous types into list. anonymous types is contain of List, String, and DateTime. I tried with the code as below but its giving an error. please help and tell me what I am missing or suggest how can I achieve this.

//Error:

System.InvalidCastException: Specified cast is not valid..

//Edited C# Linq Code

        public List<AuditInfo> GetScanAudit(object Id, DateTime? fromTime, DateTime? toTime, string type = null,
            string user = null, Pager pager = null)
        {
            using (var ctx = new PlantDataContext())
            {
                var query = from audit in ctx.AuditLog
                            join ent in ctx.Scans on audit.RecordId equals ent.Id.ToString() into audits
                            from entaudits in audits.DefaultIfEmpty()
                            where audit.TypeFullName == "ABCD.DB.Model.Scan"
                            select new
                            {
                                audit,
                                entaudits
                            };

                if (Id != null)
                {
                    query = query.Where(x => x.audit.RecordId == Id.ToString());
                }
                if (fromTime.HasValue)
                {
                    var tmp = new DateTimeOffset(fromTime.Value.ToUniversalTime());
                    query = query.Where(x => x.audit.EventDateUTC >= tmp);
                }
                if (toTime.HasValue)
                {
                    var tmp = new DateTimeOffset(toTime.Value.ToUniversalTime());
                    query = query.Where(x => x.audit.EventDateUTC <= tmp);
                }
                if (!string.IsNullOrEmpty(type))
                {
                    var parseEvent = (EventType)Enum.Parse(typeof(EventType), type);
                    query = query.Where(x => x.audit.EventType == parseEvent);
                }
                if (!string.IsNullOrEmpty(user))
                {
                    query = query.Where(x => x.audit.UserName == user);
                }
                if (pager != null)
                {
                    var totalRecords = query.Count();
                    pager.TotalRecords = totalRecords;
                    var data = query.Select(x =>
                        new AuditInfo
                        {
                            x.audit.TypeFullName, //Here Error Occurs
                            x.audit.UserName,//Here Error Occurs
                            x.audit.EventType,//Here Error Occurs
                            x.audit.EventDateUTC,//Here Error Occurs
                            @LogDetails = x.audit.LogDetails.ToList(), //Here Error Occurs
                            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
                        {
                            x.audit.TypeFullName,
                            x.audit.UserName,
                            x.audit.EventType,
                            x.audit.EventDateUTC,
                            @LogDetails = x.audit.LogDetails.ToList(),
                            x.entaudits.Name,
                            @Description = x.entaudits.Description
                        })
                            .OrderByDescending(x => x.EventDateUTC)
                        .ToList<AuditInfo>();
                    return list;
                }
            }
        }

When I debug the code totalRecords variable showing count 6, but is showing exception with message Specified cast is not valid at this line var list1 = data.ToList();

21
  • 1
    Not really sure the sql tag is relevant here Commented Oct 30, 2018 at 9:18
  • @CaiusJard, seems like OP wants us to convert from Linq to SQL. Commented Oct 30, 2018 at 9:20
  • Change your method's return type to something else: a strongly type class, or C#7 value tuples. Commented Oct 30, 2018 at 9:21
  • where do you want to use this method => GetScanAudit and why you choose return type List<dynamic> and why not List<SomeClass>? Commented Oct 30, 2018 at 9:28
  • 2
    What is the point to return dynamic? C# is a strongly typed programming language and there is no need for your case to return List of dynamic. If you are new to C# you should know that strong types are good, while you should avoid dynamic. Commented Oct 30, 2018 at 9:37

2 Answers 2

9

You have to cast the anonymous objects to dynamic.

To do this with linq you can use Cast<dynamic> linq method:

var list = query.Select(x =>
    new
    {
        x.audit.TypeFullName,
        x.audit.UserName,
        x.audit.EventType,
        x.audit.EventDateUTC,
        @LogDetails = x.audit.LogDetails.ToList(),
        x.entaudits.Name,
        @Description = x.entaudits.Description
    })
    .OrderByDescending(x => x.EventDateUTC)
    .AsEnumerable()
    .Cast<dynamic>()
    .ToList<dynamic>(); \\ here exception occures
return list;
Sign up to request clarification or add additional context in comments.

4 Comments

Not working sir. An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code Additional information: Unable to cast the type 'Anonymous type' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types. occurred
@SandyN you can use .AsEnumerable() instead of .Cast<dynamic>.
still not working sir, An exception of type 'System.InvalidCastException' occurred in System.Data.dll but was not handled in user code Additional information: Specified cast is not valid. occurred
Using AsEnumerable() and Cast<dynamic>() works for me
4

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;
            }

18 Comments

Thank you sir I will try this one.
@SandyN, let me know if it help or not?
Sure sir. I will do.
make sure that => if you x.audit.TypeFullName is string then in class TypeFullName will be string and if x.audit.EventDateUTC is DateTime then in class EventDateUTC is DateTime means you must assign proper datatype to class property that should match in your select clause query
Yes sir I created another Class file for that
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.