I get Anonymous type members must be declared with a member assignment when casting to shortdate?

StackOverflow https://stackoverflow.com/questions/23188855

  •  06-07-2023
  •  | 
  •  

Domanda

I am using .net 3.5 WCF, I need to cast the date field "r.DateReceived" to shortdate. When I try use .toShortDateString(), I get the warning "Anonymous type members must be declared with a member assignment". The results will be converted to Json.

var json = from r in results
                       select Convert(new
                       {
                           r.CaseId,
                           r.TamisCaseNo,
                           r.TaxPdr,
                           r.OarNo,
                           r.Tin,
                           r.DateReceived,
                           r.IdrsOrgAssigned,
                           r.IdrsTeAssigned,
                           r.DateRequestComp
                       });
È stato utile?

Soluzione

From MSDN:

If you do not specify member names in the anonymous type, the compiler gives the anonymous type members the same name as the property being used to initialize them. You must provide a name for a property that is being initialized with an expression

So the property names of anonymous types can only be inferred if your initializer is binding directly to a property or field. If you're calling a method or have some some other kind of expression, you'll need to specify the property name explicitly, like this:

var json = from r in results
                   select Convert(new
                   {
                       r.CaseId,
                       r.TamisCaseNo,
                       r.TaxPdr,
                       r.OarNo,
                       r.Tin,
                       DateReceived = r.DateReceived.ToShortDateString(),
                       r.IdrsOrgAssigned,
                       r.IdrsTeAssigned,
                       r.DateRequestComp
                   });

Altri suggerimenti

Another option, in case you have a variable that should be nullable and you're making a query via EF to a DB and the compiler interprets the call as non-nullable but the runtime throws a nullable object must have a value error:

            var queryResults = query
                .Select(
                    g => new
                    {
                        g.Id,
                        g.Latitude,
                        g.Longitude,
                        ParentId = (long?)g.ParentObj2Objs.FirstOrDefault().ParentId
                    })
                .ToList();

You see, ParentId is not nullable on type ParentObj2Objs, so compiler would be like "ParentId" is of type Int64 on the anonymous type. Except "FirstOrDefault()" can return null, and thus the query errors out. But forcing it to (long?), you avoid the issue as ProviderId on the anonymous type is interpreted correctly.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top