I'm using the PagedList.Mvc NuGet Package for paging, In a View everything seems to works perfectly nice but in my controller this error occurs
'System.Collections.Generic.List<CreateSocial.Models.UserProfiles>' does not contain a definition for 'ToPagedList' and no extension method 'ToPagedList' accepting a first argument of type 'System.Collections.Generic.List<CreateSocial.Models.UserProfiles>' could be found (are you missing a using directive or an assembly reference?)
even though I defined the namespace like:
using PagedList;
using PagedList.Mvc;
my code look like this:
[HttpGet]
public ActionResult Results(SearchViewModel svm, int CurrentPage)
{
const int ResultsPerPage = 50;
List<UserProfiles> results = db.UserProfiles.Where(w => w.FirstName.Contains(svm.SearchStr) || w.LastName.Contains(svm.SearchStr)).ToList();
return View(results.ToPagedList(CurrentPage, ResultsPerPage));
}
I tried deleting and adding PagedList again via Package Manager Console. But I can't seem to fix it. What could be causing this and how to fix it? Hope you guys can give any suggestions. Thanks in advance!
First of all don't use ToList()!
If you have like 10.000 records in database it will first load them to memory and then execute method ToPagedList
If you look in pagedlist extensions definition then you will see that you can also use iqueryable
// Summary:
// Creates a subset of this collection of objects that can be individually accessed
// by index and containing metadata about the collection of objects the subset
// was created from.
//
// Parameters:
// superset:
// The collection of objects to be divided into subsets. If the collection implements
// System.Linq.IQueryable<T>, it will be treated as such.
//
// pageNumber:
// The one-based index of the subset of objects to be contained by this instance.
//
// pageSize:
// The maximum size of any individual subset.
//
// Type parameters:
// T:
// The type of object the collection should contain.
//
// Returns:
// A subset of this collection of objects that can be individually accessed
// by index and containing metadata about the collection of objects the subset
// was created from.
public static IPagedList<T> ToPagedList<T>(this IQueryable<T> superset, int pageNumber, int pageSize);
About yours problem, check if you have referenced pagedlist and pagedlist.mvc. Also try rebuild project and check if any other errors are shown
You're probably missing a "using xxxxxx" namespace.
using PagedList;
These are usually "extension methods"......and while they extend something that you probably already have a "using" statement for...the extension method itself is probably in another namespace (thus requires an additional "using" statement).
APPEND
You mention "I tried deleting and adding PagedList again via Package Manager Console"
When you do this, there is a drop down box for the target project. Make sure you have the correct csproj listed in the drop down box.
To make super sure you have the reference, open up your proj file (csproj) in notepad or notepad++ and look for the reference.
Related
I am writing a C# console application project (.NET 7.0) using Visual Studio for macOS 2022 v17.4 and System.CommandLine (2.0.0-beta4.22272.1).
I am trying to add a custom validator to one of my Commands, and found the following code snippet on the project's GitHub site:
this.AddValidator(commandResult =>
{
if (commandResult.Children.Contains("one") &&
commandResult.Children.Contains("two"))
{
commandResult.ErrorMessage = "Options '--one' and '--two' cannot be used together.";
}
});
However, it will not compile in my command, due to Error CS1929: 'IReadOnlyList' does not contain a definition for 'Contains' and the best extension method overload 'MemoryExtensions.Contains(ReadOnlySpan, string)' requires a receiver of type 'ReadOnlySpan' (CS1929).
I have looked for the appropriate extension method in the various System.CommandLine namespaces, but I don't see anything. (Yes, I included the System.Linq namespace.)
Can anyone suggest what is amiss?
Edit: The original code which I "borrowed" is this:
command.AddValidator(commandResult =>
{
if (commandResult.Children.Contains("one") &&
commandResult.Children.Contains("two"))
{
return "Options '--one' and '--two' cannot be used together.";
}
return null;
});
Note that this delegate returns a value, while the updated one does not, but instead sets ErrorMessage. That's one breaking change in System.CommandLine, and it's plausible that the issue here is due to another breaking change. The System.CommandLine project does note that the project is in a state of flux and subject to changes.
I have no experience with this specific library, but peeking its source hints that the collection you are calling .Contains() on doesn't contain Strings, but rather instances of SymbolResult, hence it cannot find suitable overload for the method you are trying to call.
I couldn't find the code you provided anywhere from mentioned GitHub repo, but instead found this piece of code from this test file of library:
command.Validators.Add(commandResult =>
{
if (commandResult.Children.Any(sr => sr.Symbol is IdentifierSymbol id && id.HasAlias("--one")) &&
commandResult.Children.Any(sr => sr.Symbol is IdentifierSymbol id && id.HasAlias("--two")))
{
commandResult.ErrorMessage = "Options '--one' and '--two' cannot be used together.";
}
});
The extension method you need is defined as part of the class System.Linq.Enumerable. So you need using System.Linq; at the top of your class file.
But that won't help if your project doesn't reference the assembly System.Linq.dll. (I don't know why it wouldn't, just out of the box, but perhaps it doesn't.) So you may need to add a reference for that.
In a template which generates code dynamically based on certain conditions, some of the code uses types which require additional using statements to compile correctly. How do I reference/use such a type such that the using will be included in the generated output iff that specific code is generated?
e.g. Given this code, how would I make sure the correct using is added?
if (attribute.IsEnum()) {
// Resolve the EnumToStringConverter type?
statements.Add($".HasConversion(new EnumToStringConverter<{attribute.Type.Element.Name}>());");
}
One way to do this is to use the UseType(...) method that is available on the CSharpTemplateBase base class (available in Intent.Modules.Common.CSharp.3.0.10 nuget package).
For example, you could try something like this:
if (attribute.IsEnum()) {
// Resolve the EnumToStringConverter type?
statements.Add($".HasConversion(new {UseType("EnumToStringConverter", "<your-required-namespace>"}<{attribute.Type.Element.Name}>());");
}
There is also another overload which would take in the fully qualified name. For example:
UseType("Microsoft.EntityFrameworkCore.Storage.ValueConversion.EnumToStringConverter")
(assuming you're using the EnumToStringConverter from EF Core)
I have defined attribute MyAttribute : Attribute that is supposed to be used exactly once within a class (only one constructor per class may have it and it can appear only once on ctor’s attribute list).
I have created a Roslyn analyzer to check this which marks every usage of such attribute (if used more than once) and allows user to pick fixture called "Leave this attribute occurrence and delete all others".
Now within FixProvider I need to return new modified Solution. It's not difficult to modify every Document that requires the fix (by using SyntaxRewriter to modify SyntaxTree inside). However, I have no idea how to modify Solution or Project - they don't have any method like "ReplaceProject"/"ReplaceDocument".
How to do that?
You could replace the text of a document using the following method:
solution = solution.WithDocumentText(currentDocument.Id,
currentDocumentSyntaxTree.GetText());
To clear up the obvious first, I am:
using System.Linq;
using System.Collections.Generic;
Have a project reference to System.Core
My DbSet and DbContext classes are defined properly
The strange thing is, intellisense sees it, but I have a compiler warning and it won't compile.
I have tried cleaning the project first, restarting Visual Studio, etc and it still is complaining about:
Error CS1929 'DbSet' does not contain a definition for 'ToList' and the best extension method overload 'Enumerable.ToList(IEnumerable)' requires a receiver of type 'IEnumerable'
My "receiver" in this case is the compiler statically-determined var.
This is a new laptop and a fresh Visual Studio install ... is there something obvious I am missing here?
I wanted these internal but tried switching everything pubilc just to be sure, but I am getting the same error.
Most people report this when they are missing the using clause for Linq but I have that, and intellisense sees it which is where I am getting confused.
Line in question:
var excludedUrls = db.ExcludedUrls.ToList<string>();
I assume that in your code db is a Dbcontext with a property ExcludedUrls of type DbSet<TEntity>
DbSet<TEntity> implements IEnumerable<TEntity> If you have included LINQ, you can use the extension method Enumerable.ToList<TEntity>().
Because of your error I assume that TEntity is not a string. Your code will compile if you leave out the part:
var excludedUrls = db.ExcludedUrls.ToList();
However, this might not give a list with the elements you want. Somehow you'll have to convert each excludedUrl in your source sequence to the string representation that you want. If ToString() does not do this, you'll have to create a function yourself:
class MyDbContext : DbContext
{
public DbSet<MyTSource> ExcludedUrls {get; set;}
}
void string Transform(MyTSource excludedUrl)
{
...
}
List<string> result = dbContext.ExcludedUrls
.Select(excludedUrl => Transform(excludedUrl)
.ToList();
In words: from the sequence of excludedUrls, take each element, and transform it to a string using Transform. Convert the resulting sequence of strings to a list, which will be a list of strings
By the way, did you notice I used ToList without mentioning <string>? The compiler is able to detect the type of the elements in your input sequence, and can create a List of the same type of elements.
Consider avoiding mentioning the TSource when using the Linq functions. This has several advantages:
less typing
Easier to change the source sequence, or intermediate linq statements
Easier to detect the resulting type (and thus easier to detect the error you mentioned)
It allows the use of anonymous types
The answer, it turns out, is not calling the generic form of ToList<> here, but instead calling straight ToList(), which returns a generic List<ExcludedUrl>. A thank you to Ivan Stoev in the comments section for the tip.
I was relying too much on Intellisense hints here and not enough on memory.
As you can see, due to the way extension methods work, it presented me with a ToList in its generic form, which is why my code was written the way it was.
I dont know a whole lot about C# but I have this project I am working on where I would like to do something like this:
SortedDictionary<int, List<ChessMove>> possibleMovesByRank = new SortedDictionary<int, List<ChessMove>>();
...
var best = possibleMovesByRank.Keys.Last();
From what I have been able to find, this should use linq to return the key that has the highest value, however VS is giving me an error:
SortedDictionary.KeyCollection does not contain a definition for 'Last' and no extension method for 'Last'
Am I missing something or is my project not set up correctly or something?
Most likely, you are missing the System.Linq namespace in your C# file. This is an Extension Method and Enumerable.Last will not exist unless you include the relevant namespace.