GeekzSG
GeekzSG

Reputation: 973

error CS1061 does not contain a definition - Roslyn compilation issue

I'm using Roslyn to generate a Linq expression on a business object (let's say, Customer) with definition

public class Customer  
{
    public List<Order> Orders { get; set; }
}

The Roslyn code to compile C# code is -

var linqType = typeof(System.Linq.Enumerable);
List<MetadataReference> metadataReferences = new List<MetadataReference>()
{                  
      //Other business DLLs as well
      MetadataReference.CreateFromFile(linqType.Assembly.Location) 
};

//mscorlib
car dlls = AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES").ToString().Split(new char[] { ';' });
foreach (var platformDLL in dlls)
{       
      metadataReferences.Add(MetadataReference.CreateFromFile(platformDLL));
}

// Removed: Get Units 

var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary,
                optimizationLevel: OptimizationLevel.Debug,
                assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
                allowUnsafe: true);
compilationOptions.WithUsings(GetNamespaces());

var compilation = CSharpCompilation.Create(assemblyName: "customer",
       syntaxTrees: units.Select(x => x.SyntaxTree).ToArray(),  
       references: metadataReferences,
       options: compilationOptions);

The Linq expression generated is as below.

Exists<Customer>(f => f.Orders.Any() == true)

The class also has following using

 using System;
 using System.Text; 
 using System.Linq;

However, I'm still getting below error

error CS1061: 'Customer' does not contain a definition for 'Orders.Any()' and no extension method 'Orders.Any()' accepting a first argument of type 'Customer' could be found (are you missing a using directive or an assembly reference?)

The code gets generated correctly, but code compilation using Roslyn fails with above error. When I copy paste the generated code in Visual Studio, there are no errors on compilation

Upvotes: 0

Views: 770

Answers (1)

SLaks
SLaks

Reputation: 888047

It sounds like you created a MemberAccessExpression with the member name Orders.Any().

MemberAccessExpression can only use a single member; you need two nested expressions for that chain.

Upvotes: 2

Related Questions