This is my Query =>
var department = dataContext.Query<Department>("SELECT Id FROM tblDepartment");
I want to display the values in variable Department in ViewBag or Anywhere.How can I do that?
var department = dataContext.Query<Department>("SELECT Id FROM tblDepartment").ToList()
and then work with list
You can use linq to Entities without executing raw queries as:
var department = dataContext.Department.Select(x=>x.Id).ToList();
If you are stubborn to use raw query, you can use as teo van kot has suggested above:
var department = dataContext.Query<Department>("SELECT Id FROM tblDepartment").ToList();
You can assign the list to ViewBag in controller as:
ViewBag.DepartmentIDs = department;
You can display the values in View as:
#{
foreach(var item in ViewBag.DepartmentIDs)
{
<span>#item <br/></span>
}
}
Related
So I was working on a DropDown list and it works, but it has many duplicate emails, I just want to see distinct emails... So I tried doing .Distinct() in the model class, but that still gave me duplicates..
Model Class:
public string One_Manager_Email{ get; set; }
public List<Hello> getManagers()
{
var que = (from wr in db.View
select new Hello
{
O_Manager_Email= wr.One_Manager_Email
}).Distinct().ToList();
return que;
}
Controller Class: (This is probably where the problem is happening)
public ActionResult Index()
{
test = new Hello();
ViewBag.Managers = new SelectList(test.getManagers(), "", "O_Manager_Email");
return View(test.getStuff());
}
View Class:
<div>
#Html.DropDownList("Managers", ViewBag.Managers as SelectList)
</div>
Any help would be great, thank you!
You need to group your objects by the property you want them to be distinct by, and then select the first element of the grouping.
public List<Hello> getManagers()
{
var que = (from wr in db.View
select new Hello
{
O_Manager_Email= wr.One_Manager_Email
})
.GroupBy(g => g.O_Manager_Email) //group by property
.Select(g => g.First()) //take first element from every grouping
.ToList();
return que;
}
For some more details, you can see this post that has more details on grouping and distinct: LINQ's Distinct() on a particular property
Distinct won't work on objects like that, as objects are always distinct, but you can try using group by in your query, something along these lines:
var que = (from wr in db.View
group new {wr.One_Manager_Email}
by new {wr.One_Manager_Email} into grouped
select new Hello
{
O_Manager_Email= grouped.Key.One_Manager_Email
}).ToList();
return que;
If you just need email address, you can select just string instead of selecting Hello object. If you select Hello object and try to distinct you like that way, you obviously get duplicated items. Because every object is already unique.
I believe you have already answer. GroupBy might solve your problem. However unless you really need GroupBy, don't use GroupBy! It's really expensive operation.
In your case, you should use DistinctBy.
var distinctList = list.DistinctBy(x => x.Prop).ToList();
On your code:
var que = (from wr in db.View
select new Hello
{
O_Manager_Email = wr.One_Manager_Email
}).DistinctBy(x=>x.O_Manager_Email).ToList();
Oh, in terms of DistinctBy usage, you should import namespace of Microsoft.Ajax.Utilities.
using Microsoft.Ajax.Utilities;
I have two tables deal_outlet and vendors_outlet. I am trying to compare a list of outlet_id from deal_outlet table to vendor table but .contain method shows error has some invalid arguments. I really don't understand problem in this code.
public ActionResult Detail_of_deal(int id)
{
var d1 = db.deal_outlet.Where(x => x.outlet_id==id).ToList();
f_model.model4 = db.vendors_outlet.Where(x =>d1.Contains(x.outlet_id)).ToList();
var d = obj.detail_of_image(id,ref model);
return View(f_model);
}
Depending on the goal of the code you could try the following:
public ActionResult Detail_of_deal(int id)
{
var d1 = db.deal_outlet.Where(x => x.outlet_id==id).ToList();
f_model.model4 = db.vendors_outlet.AsEnumerable().Select(x => d1.Contains(x.outlet_id)).ToList();
var d = obj.detail_of_image(id,ref model);
return View(f_model);
}
That should make f_model.model4 a list of all the vendors_outlets that have a matching deal_outlet.id
The Linq Contains method returns true if the list contains the item passed in. You are asking to see if a list of deal_outlet objects contains an int, which obviously it won't.
Instead of projecting a collection of deal_outlets, project a list of integers:
var d1 = db.deal_outlet.Where(x => x.outlet_id==id).Select(x => x.outlet_id);
f_model.model4 = db.vendors_outlet.Where(x =>d1.Contains(x.outlet_id)).ToList();
But logically, that's the same as:
f_model.model4 = db.vendors_outlet.Where(x =>x.outlet_i==id)).ToList();
So it's not clear what you're trying to do.
EDIT
Based on your comments, I believe these are the queries you want:
i am trying to fetch list of outlet_id from deal_outlet table where deal_id equal to id,
var d1 = db.deal_outlet.Where(x => x.deal_id==id).ToList();
Now want to compare this list to vendor_outlet table and fetch those rows where outlet_id from deal_outlet table equals to outlet_id in vendor_outlet table
Get a list of ID's to match:
var ids = d1.Select(x => x.outlet_id).ToList();
And use Contains to see if the list contains any of the IDs from the related table:
f_model.model4 = db.vendors_outlet.Where(vo => ids.Contains(vo.outlet_id))
.ToList();
How one can fetch multiple columns data using neo4jClient -
For eq. the example shown on link
Cyper query to fetch multiple column collection
The sample shown above passes properties of event node for collection instead of complete event node.
The query I am constructing takes few properties from the event node and few properties from the relation.
For eq. The relation attribute "registerd_on" needs to be added.
So how to pass multiple properties for collection ?
It's not very nice, but if you look at what is returned by doing a collection you get an array of arrays, but these arrays don't have properties as such, so you can only really parse them as string.
Using the :play movies dataset as a base:
var query = gc.Cypher
.Match("(p:Person {name:'Tom Hanks'})-->(m:Movie)")
.With("p, collect([m.title, m.released]) as collection")
.Return((p, collection) => new
{
Person = p.As<Person>(),
Collection = Return.As<IEnumerable<IEnumerable<string>>>("collection")
});
where Person is :
public class Person
{
public string name { get; set; }
}
You can then access the data like so:
foreach (var result in results)
{
Console.WriteLine($"Person: {result.Person.name}");
foreach (var collection in result.Collection)
{
foreach (var item in collection)
{
Console.WriteLine($"\t{item}");
}
}
}
which is not nice :/
I'm sticking on how to best present some data that's being dynamically generated from two different tables.
Given my query:
var assets = assetRepo.Find(x => x.LoginId == User.Identity.Name);
var accounts = repository.Find(x => x.AccStatus == "A" && x.LoginId == User.Identity.Name);
var query = from asst in assets
join acct in accounts on asst.AccountId equals acct.AccountId
select new
{
Account = acct.AccountNumber,
Status = acct.AccStatus,
Make = asst.Make,
Model = asst.Model,
Submodel = asst.SubModel,
Registration = asst.Registration,
Balance = acct.BalanceOutstanding,
NextPayment = acct.NextPayment,
Date = String.Format("{0:dd MMM yyyy}", acct.NextPaymentDate),
Due = acct.ArrearsBal
};
What would be the best (i.e. cleanest) way to bind this to the view? Would a custom class be required or is there a way to specify and iterate over a collection of anonymous types?
Creating custom class can give you additional benefits. You can use DisplayAttribute to set column headers and order. Then you can create view (or template to use with DisplayFor) that takes list of objects of any type and uses reflection to read annotations and display view nicely.
class Report {
[Display(Name="Account",Order=1)]
public string Account {get; set;}
[Display(Name="Next payment",Order=2)]
public Date NextPayment {get; set;}
}
It looks also clean. You will be able to use this annotations not only for grid, but also for excel exports or other data operations.
1) I've a Product table with 4 columns: ProductID, Name, Category, and Price. Here's the regular linq to query this table.
public ActionResult Index()
{
private ProductDataContext db = new ProductDataContext();
var products = from p in db.Products
where p.Category == "Soccer"
select new ProductInfo { Name = p.Name, Price = p.Price}
return View(products);
}
Where ProductInfo is just a class that contains 2 properties (Name and Price). The Index page Inherits ViewPage - IEnumerable - ProductInfo. Everything works fine.
2) To dynamicaly execute the above query, I do this:
Public ActionResult Index()
{
var products =
db.Products
.Where("Category = \"Soccer\"")
.Select(/* WHAT SOULD I WRITE HERE TO SELECT NAME & PRICE?*/)
return View(products);
}
I'm using both 'System.Lind.Dynamic' namespace and the DynamicLibrary.cs (downloaded from ScottGu blog).
Here are my questions:
What expression do I use to select only Name and Price?
(Most importantly) How do I retrieve the data in my view? (i.e. What type the ViewPage inherits? ProductInfo?)
===================
EDIT
When I write .Select("new(Name, Price)"), I'm able to pass an object to the ViewData's Model property. Unfortunately, in order to use the Viewdata object, I'm asked to cast the Viewdata to a type. But, I do not know how to determine the type to do the casting.
====================
EDIT
Instead of the ViewData's Model property, I'm using simply the ViewData["products"]. To retrieve the content, I just place a IEnumerable cast before the ViewData, like this:
<% foreach(var item in (IEnumerable)ViewData["products"]){%>
<p><% = Html.Encode(item)%><p>
<%}%>
There are 2 situations:
1) If I select only one column (for instance, Name), everything work fine.
2) If I select more than 1 more columns (Name, Price), I get something like this
{Name=Soccer, Price=19.50}
{Name=Shin Pads, Price=11.59}
Why I just don't get something like
Soccer, 19.50
Shin Pads, 11.59
=================================
EDIT April 02 - 05h47 AM
I've define the GetPropertyValue Method (as your response suggets) as static in a static Class that I called 'HelperClass'. Now, this is the way I try to access the value of Name from my object.
<% = Html.Encode(HelperClass.GetPropertyValue(ViewData["product"], "Name")) %>
I get the following Exception:"Object reference not set to an instance of an object". And, the following line from the inside GetPropertyValue() his highlight.
Line 22: return propInfo.GetValue(obj, null);
Do I need to use new keyword? (where?)
Thanks for helping
Private Sub filter()
Dim coll = db.Products.Where(Function(x) x.Category.Equals("Soccer")) _
.Select(Function(x) GetObject(x.Name, x.Price))
End Sub
Private Function GetObject(ByVal name As String, ByVal price As String) As Object
Return new ProductInfo(name, price)
End Function
1) To generate a new projection type at runtime you can:
.Select("new(Name, Price)")
2) To read values from the object, you need to use reflection:
string name = GetPropertyValue(someObject, "Name");
...
public static object GetPropertyValue(object obj, string propName)
{
System.Reflection.PropertyInfo propInfo = obj.GetType().GetProperty(propName);
return propInfo.GetValue(obj, null);
}