it will give me error Unable to cast object of type.
public class CusInfomration
{
public string CustomerName { get; set; }
public string CustomerID { get; set; }
public string OrderDate { get; set; }
public string OrderId { get; set; }
}
var CustomerFromWash = from p in _NorthWindDataContext.Customers
join q in _NorthWindDataContext.Orders
on p.CustomerID equals q.CustomerID
where p.Region == "WA"
select new
{
CustomerName =Convert.ToString(p.CompanyName),
CustomerID = Convert.ToString(p.CustomerID),
OrderId = Convert.ToString(q.OrderID),
OrderDate = Convert.ToString(q.OrderDate),
};
List<cusinfomration> lstCust = (List<cusinfomration>)CustomerFromWash;
That LINQ query returns an IQueryable<T>. IQueryable<T> is an interface and List<T> does not implement it, so there is no way that the underlying, concrete implementation is a List<T> (it does however implement IEnumerable<T>, so a cast to that would be valid). Even if it were it would not be a safe cast to make as the .NET folks may want to change out the underlying implementation someday and your cast would be broken. Not a good idea even if it did work initially.
You can call ToList() on the return value of the LINQ query:
var CustomerFromWash = (from p in _NorthWindDataContext.Customers
join q in _NorthWindDataContext.Orders
on p.CustomerID equals q.CustomerID
where p.Region == "WA"
select new
{
CustomerName =Convert.ToString(p.CompanyName),
CustomerID = Convert.ToString(p.CustomerID),
OrderId = Convert.ToString(q.OrderID),
OrderDate = Convert.ToString(q.OrderDate),
}).ToList();
Even then though you are selecting a collection of anonymous types, not CustInformation objects. If you want CustInformation objects to be returned then you will need to:
select new CustInformation
{
// set properties here
}
Related
In teh .NET SDK your create record method passes a 0 for id on all records as this is unknown until teh response comes back with the id's populated etc
It Seems that the JSON DefaultValueHandling = DefaultValueHandling.Ignore is not working on the freshly minted int '0' id's
An therefore the body has the id:0 and trys inserts the records with id:0 on all and trips a Unique constraint on the inner exception in fiddler
I had a similar problem with DreamFactory
I added a conditional Property Serialization attribute to the Poco/DTO for the staff record as an example
internal class StaffRecord
{
public bool ShouldSerializeUid()
{
return Uid != 0;
}
public int Uid { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public bool Active { get; set; }
public override string ToString()
{
return string.Format("{0}: name = {1} {2}, age = {3}, active = {4}", Uid, FirstName, LastName, Age, Active);
}
}
This now works as expected on both serialization/deserialization
Here is the docs in the JSON.NET docs
Conditional Property Serialization
Cheers :D
there are two tables named project and city like this:
public class Project
{
[Key]
public int ProjectId { get; set; }
public string ProjectName { get; set; }
public int CityID { get; set; }
public City City { get; set; }
}
public class City
{
[Key]
public int CityID { get; set; }
public string CityName { get; set; }
public ICollection<Project> Projects { get; set; }
}
Here, CityID in the project class is the foreign key to City class joining both tables.I have properly configured and checked that both are inter connected to each other.
Now, i have a Json action method to fetch the Desired property like this:
public JsonResult GetProjects()
{
var ret = (from project in db.Projects.ToList()
orderby project.ProjectId
select new
{
CityName = project.City.CityName,
ProjectId = project.ProjectId
}).AsEnumerable();
return Json(ret, JsonRequestBehavior.AllowGet);
}
here, i am trying to push out the cityName but i am unable to get back cityname.It is giving System.NullRefernceException at line CityName = project.City.CityName.Please suggest me what to do now. Is something wrong in my code. i am able to get other properties.
Whe you use somehting like .ToList(), .ToArray(), and so on, you are materializing the query. In LINQ to EF materailizing the query means running the SQL query and populating your classes with the data received form the DB. From that point on, there is no chance that the following referred properties are retrieved from the dtabase.
LINQ to EF uses IQueryable<T> interface. An IQueryable<T> is a "potential query" that has not already been "executed". While you do things that doesn't materialize the query, your query will keep being a IQueryable<T> and it won't be executed in the DB.
There is also another thing that materializes the queryable: enumerating it.
So, what you need to is to not materialize the query until you have provided all the information necessary to run the query. In this case you have to remove the .ToList()
I am looking at trying to use a Linq query to determine if the following JSON is true if it contains a product that has a SKU of 12345 OR a TypeCode of "C".
"[{\"SKU\":\"12345\",\"Description\":\"Test Part 12345\",\"TypeCode\":\"A\",\"Cost\":24.99},{\"SKU\":\"54567\",\"Description\":\"Test Part 54567\",\"TypeCode\":\"B\",\"Cost\":9.99},{\"SKU\":\"QWZ2342\",\"Description\":\"Test Part QWZ2342\",\"TypeCode\":\"C\",\"Cost\":19.99}]"
I have been working with the Json.net (http://james.newtonking.com/projects/json-net.aspx)
At first, you have to deserialize the JSON into a C# object, lets say Product.
class Product
{
public int SKU { get; set; }
public string Desc { get; set; }
public string TypeCode { get; set; }
public decimal Cost { get; set; }
}
then, using .NET's JavaScriptSerializer (System.Web.Script.Serialization), convert the json string to become List of your custom objects.
string json = "[{\"SKU\":\"12345\",\"Description\":\"Test Part 12345\",\"TypeCode\":\"A\",\"Cost\":24.99},{\"SKU\":\"54567\",\"Description\":\"Test Part 54567\",\"TypeCode\":\"B\",\"Cost\":9.99},{\"SKU\":\"QWZ2342\",\"Description\":\"Test Part QWZ2342\",\"TypeCode\":\"C\",\"Cost\":19.99}]"
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
List<Product> productList = new List<Product>();
productList = jsonSerializer.Deserialize<List<Product>>(json);
the last step, using simple linq query, you cant check whether your product exist on the list:
var Found = from o in productList
where o.SKU == 12345
select o.SKU;
if (Found.Count() > 0)
return true;
else
return false;
I have a table of Items for auction and a table of bids made for those items. There's much more to the database but we'll keep it simple.
public class Items
{
public int ItemID { get; set; }
public string ItemName { get; set; }
public List<Bid> Bids { get; set; }
}
public class Bids
{
public int BidID { get; set; }
public int ItemID { get; set; }
public decimal Amount { get; set; }
public datetime BidTime { get; set; }
public int CustomerID { get; set; }
}
I want to return a dataset that includes the ItemID, the ItemName and all of the associated bid records ordered by BidTime, descending. Finally, I'd like to only see Items that a certain Customer has bid on and I'd like to only see their bids for that item. There is a foreign key relationship between Bids.ItemID and Items.ItemID. I'm using Linq to SQL.
This works and appears to return the correct dataset:
from i in Items
from b in i.Bids
where i.AuctionID == 2 && b.CustomerID == (Int32?)1165
orderby b.BidTime descending
select new
{
i.ItemID,
i.ItemName,
i.Bids
}
I'm a SQL guy trying to wrap my head around the OO nature of Linq. Is this the best way (or even a good way) to get the results I want? Is there a better way?
Thanks,
BK
How about this one (slightly more simple syntax):
Updated where clause due to comment
from i in db.items
where i.AuctionID == 2 && i.Bids.Any(c=>c.CustomerID == (Int32?)1165)
select new
{ i.ItemId,
i.ItemName,
i.Bids.Where(b=>b.CustomerID == (Int32?)1165 ).OrderbyDescending(b=>b.BidTime)
}
Make sure you profile the sql and verify that you get only ONE sql statement. If not, you need to have to add LoadOptions to your datacontext (that will make sure all the bids are eager loaded with your items).
This one will also order the bids per item (not sure if yours will do the same.... but I guess you checked that).
Given this in my datacontext:
public class EventsForUserID
{
public string eventName { get; set; }
public int eventID { get; set; }
public string eventIdentifier { get; set; }
public DateTime eventOpenDate { get; set; }
public DateTime eventCloseDate { get; set; }
public bool eventDisabled { get; set; }
public EventsForUserID() {}
public EventsForUserID(string pEventName, int pEventID, string pEventIdentifier, DateTime pEventOpenDate, DateTime pEventCloseDate, bool pEventDisabled)
{
this.eventName = pEventName;
this.eventID = pEventID;
this.eventIdentifier = pEventIdentifier;
this.eventOpenDate = pEventOpenDate;
this.eventCloseDate = pEventCloseDate;
this.eventDisabled = pEventDisabled;
}
}
public List<EventsForUserID> GetEventsForUserID(string userID, bool excludeDisabled)
{
var e =
from ex in this.Exhibitors
join ev in this.Events on ex.EventID equals ev.EventID
where ex.UserID.ToString() == userID
select new EventsForUserID (
ev.EventName,
ev.EventID,
ev.EventID + "[::]" + ex.ExhibitorID + "[::]" + ex.AccountDisabled + "[::]" + ev.EventDisabled,
ev.OpenDate.Value,
ev.CloseDate.Value,
ev.EventDisabled
);
if (excludeDisabled) {
e = from ev in e
where ev.eventDisabled != true
select ev;
}
return e.ToList();
}
I get the error:
The member 'LeadsDataContext+EventsForUserID.eventDisabled' has no supported translation to SQL.
on the return.ToList() line.
I've tried all sorts....AsQueryable() etc
I figure it because EventsForUserID is not a true sql table, but then I thought LINQ was for performing queries over many type of object.
Am I missing a cast of some sort.
Many thanks, N
Unfortunately you cannot mix linq-to-objects and linq-to-sql freely in the same query. If you are running the query as a linq-to-sql query, everything must be translated to sql.
Try to split your code into two queries. The first one should retrieve the relevant data from the database using linq-to-sql. The second uses linq-to-objects to do the final filtering/manipulation of data.