I have to bind the search results in the grid view based on search criteria. In my database primary store id value is like 10,12. When I select particular primary store id from the dropdown list i.e. 10, the search result corresponding to that primary store id need to be shown in the grid view.How to do that?
public static List<SearchKeyWord> GetAllKeywords(string key,
string primaryStoreId, string keywordStatus, int keywordId,
string categoryName, string subCategoryName)
{
keys = db.SearchKeyWords.Where(c => c.KeyWord.Contains(key) &&
(c.PrimaryStoreID == primaryStoreId ||
c.PrimaryStoreID.Split(',').ToList().Contains(primaryStoreId)) &&
(string.IsNullOrEmpty(categoryName) || c.StoreCategoryMapping == categoryName) &&
(string.IsNullOrEmpty(subCategoryName) || c.StoreSubCategoryMapping ==
subCategoryName)).ToList();
}
Edited!
Assumption -- search db.SearchKeyWords for all elements in which attribute PrimaryStoreID (a comma separated list) contains Key.
public static List<SearchKeyWord> GetAllKeywords(string key,
string primaryStoreId, string keywordStatus, int keywordId,
string categoryName, string subCategoryName)
{
return db.SearchKeyWords
.Where(c => c.PrimaryStoreID.Split(",".ToCharArray()).Contains(key));
}
Not clear at all what you want to do with the other parameters.
Related
I have the following list.
Public Class Car
{
int id;
string info;
}
List<Car> cars = {
new Car(1, "[{'color': 'blue','model': 'toyota'}]"),
new Car(2, "[{'color': 'red','model': 'tesla'}]"),
new Car(3, "[{'color': 'green','model': 'honda'}]")
}
I want to return the id(3) of the Honda.
Do I need to convert the whole list to a Json, then query for the specific item.
Or can I do something like
var chosenCar = cars.Where(s => JObject.Parse(s.info)["model"].Value == "honda");
I am creating a site which is personel blog. I want to give a specific routing when I enter a new blog in admin panel. Normally when I save it matches the database id. I do not have access to static routing anyway.
I want the link parameter to be stored in the database when the blog is being entered via the routing
Default : localhost/ControlName/ActionName/id (localhost/Blog/GetBlogs/2)
bu I want that
Wanted : localhost/ControlName/ActionName/storedValue(localhost/Blog/GetBlog/bluesky)
or
localhost/storedValue(localhost/bluesky)
What you're talking about is a slug. You just have to add a property on your blog class to hold some unique string value that will compose part of the URL. For example:
[Index]
[StringLength(80)]
public string Slug { get; set; }
Then, when creating the blog, you either manually specify the value for Slug (make it a field in the form) or compose it by "slugifying" the title of the blog or something. I use the following string extensions:
public static string RemoveDiacritics(this string s)
{
s = s ?? string.Empty;
if (s.Length > 0)
{
char[] chars = new char[s.Length];
int charIndex = 0;
s = s.Normalize(NormalizationForm.FormD);
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
chars[charIndex++] = c;
}
return new string(chars, 0, charIndex).Normalize(NormalizationForm.FormC);
}
return s;
}
public static string Slugify(this string s, int maxLength = 80)
{
s = s ?? string.Empty;
//First to lower case
s = s.ToLowerInvariant().RemoveDiacritics();
//Replace spaces
s = Regex.Replace(s, #"\s", "-", RegexOptions.Compiled);
//Remove invalid chars
s = Regex.Replace(s, #"[^a-z0-9s\-_]", "", RegexOptions.Compiled);
//Trim dashes from end
s = s.Trim('-', '_');
//Replace double occurences of - or _
s = Regex.Replace(s, #"([\-_]){2,}", "$1", RegexOptions.Compiled);
while (s.Length > maxLength)
{
var pieces = s.Split('-');
pieces = pieces.Take(pieces.Count() - 1).ToArray();
s = string.Join("-", pieces);
}
return s;
}
Then, for example, you could do something like:
blog.Slug = blog.Title.Slugify();
However you create the slug, you'll then use the URL param to look up the blog by that:
public ActionResult GetBlog(string slug)
{
var blog = db.Blogs.SingleOrDefault(m => m.Slug == slug);
This is why the Slug property is decorated with [Index] above. That makes EF create an index for the column when it creates the table/adds the column. Any column you intend to query on should be indexed for performance reasons. Also, you have to define a set length for the column, as NVARCHAR(MAX) (the default column type for a string) cannot be indexed.
I have a ListView which is filled with artwork names (from SQLite database), these are strings and the names are not primary keys (not unique). Of course each artwork has its own ID (primary key).
What I do, I select one artwork from this list and pass it as a string argument to a button, which creates additional informations (that is not neccessary for this question).
But I select the name, now I need to get the ID from this selected artwork as foreign key.
Of course I can create a select query like this:
"select * from Artwork where Name = ?";
and then get the ID from the artwork with this name, but as I said before, there can be multiple artworks with the same name, so this is not good.
The Plan B which I have is to display in the ListView also the IDs of the the artworks, then If you select one artwork, you could slice the String at " " and take work with the list argument which contains the ID.
But that does not feel right.
Thanks! I hope you understood what I need, if not I could provide code, but there is really a lot.
You are confusing what is displayed in the list view (the data) with how it is displayed (the view). You want the data to consist of objects containing both the id and the name. You want the view to simply display the name of those objects.
Create a class representing the Artwork that contains both the id and the name:
public class Artwork {
private final int id ;
private final String name ;
public Artwork(int id, String name) {
this.id = id ;
this.name = name ;
}
public String getName() {
return name ;
}
public int getId() {
return id ;
}
}
Have your database code return a list of Artwork objects, and define your list view:
ListView<Artwork> listView = new ListView<>();
listView.getItems().addAll(getArtworkFromDatabase());
Finally, to configure how the list view is displayed, set the cell factory:
listView.setCellFactory(lv -> new ListCell<Artwork>() {
#Override
public void updateItem(Artwork artwork, boolean empty) {
super.updateItem(artwork, empty) ;
setText(empty ? null : artwork.getName());
}
}
Now you can get whatever data you need from the selected item:
Artwork selected = listView.getSelectionModel().getSelectedItem();
int selectedId = selected.getId();
String selectedName = selected.getName();
As a part of online shopping, I implemented a cart using Session.
I have implemented the Cart in the following manner :
Session[pname] = qty;
where pname is a string variable which holds the name of the product and I used that as the key. qty is an integer variable which holds the number of items of that particular product.
To display the cart items I simply used the following loop :
foreach(string keys in Session.Keys)
Through this I get the names of the products along with the associated quantity and using this I display the cart items. The problem arises when I also have a session for the user active on the same page.
Session["uname"] = user_name;
And while retrieving the keys using Session.Keys, the uname gets included which I don't want as I need only the product's names. Is there any way I can read the keys from Session[pname] without reading from Session["uname"]?
Instead of storing an object in session for each product and quantity, just store a single object (e.g. List) which contains all of your cart items.
Here is an example which you could tweak to meet your needs:
First, a simple object to store the data:
public class CartItem {
public string Name { get; set; }
public int Quantity { get; set; }
}
Then if you need to add an object to the cart list:
var cartItems = new List<CartItem>();
cartItems.Add(new CartItem() {
Name = "",
Quantity = 1
});
Session["Cart"] = cartItems;
//Need to fetch the cart items later on?
cartItems = (List<CartItem>)Session["Cart"];
Obviously this can be implemented differently and this was just a quick example.
You mentioned needing an easier fix than what Justin Helgerson said, so here's a couple of suggestions, but they feel a little quick and dirty. Justin's is probably the superior solution. I used a quick Console app to demonstrate this, so place your constants where they belong, and you obviously don't have to create a dictionary.
const string USERSESSION = "uname";
Dictionary<string, object> session = new Dictionary<string, object>();
session["item1"] = 2;
session["item2"] = 1;
session[USERSESSION] = "StackOverflowUser";
// print cart items - minus the user name session key
foreach (string key in session.Keys.Where(s => s != USERSESSION))
{
Console.WriteLine("Key: {0} Value: {1}", key, session[key]);
}
Alternatively, if you plan on there being more keys than just "uname", use the Linq Except method.
// build up except set
List<string> exceptKeys = new List<string>
{
USERSESSION
};
foreach (string key in session.Keys.Except(exceptKeys))
{
Console.WriteLine("Key: {0} Value: {1}", key, session[key]);
}
Hi I am looking for best method for writing Dynamic LINQ query.
I have a function like
public IQueryable<Student> FindByAllStudents(int? id, string Name, int? CourseID, bool? IsActive) // like this way, all field values are passed
{
// code for compairision
return db.Student;
}
we can also write db.Students.where(predicate)
or
a query like
var students = from s in db.students where s.Name.Contains(Name)
s.ID.Equals(id)
//and so on....
So will this method works if i don't pass ID (i.e. Null)?
is proper way for all the datatypes?
The point is function can have all null values as a parameter for equivalence of select * from statement.
can any one help me to build best query with sample code?
Okay, it's not entirely clear what you want, but if you're trying to only add where clauses for the parameters which are non-null, you could do:
public IQueryable<Student> FindByAllStudents
(int? id, string name, int? courseID, bool? isActive)
{
IQueryable<Student> query = db.Student;
if (id != null)
{
query = query.Where(student => student.ID == id.Value);
}
if (name != null)
{
query = query.Where(student => student.Name.Contains(name));
}
if (courseID != null)
{
query = query.Where(student => student.CourseID == courseID.Value);
}
if (isActive != null)
{
query = query.Where(student => student.IsActive == isActive.Value);
}
return query;
}
I haven't tried that, and it's possible that LINQ to SQL would get confused by the code to find the value of the nullable value types. You may need to write code like this:
if (courseID != null)
{
int queryCourseID = courseID.Value;
query = query.Where(student => student.CourseID == queryCourseID);
}
It's worth trying the simpler form first though :)
Of course, all this gets a bit irritating. A helpful extension method could make life more concise:
public static IQueryable<TSource> OptionalWhere<TSource, TParameter>
(IQueryable<TSource> source,
TParameter? parameter,
Func<TParameter, Expression<Func<TSource,bool>>> whereClause)
where TParameter : struct
{
IQueryable<TSource> ret = source;
if (parameter != null)
{
ret = ret.Where(whereClause(parameter.Value));
}
return ret;
}
You'd then use it like this:
public IQueryable<Student> FindByAllStudents
(int? id, string name, int? courseID, bool? isActive)
{
IQueryable<Student> query = db.Student
.OptionalWhere(id, x => (student => student.ID == x))
.OptionalWhere(courseID, x => (student => student.CourseID == x))
.OptionalWhere(isActive, x => (student => student.IsActive == x));
if (name != null)
{
query = query.Where(student => student.Name.Contains(name));
}
return query;
}
Using a higher order function like this could get confusing if you're not really comfortable with it though, so if you're not doing very many queries like this you might want to stick with the longer but simpler code.