LINQ to Entities returning NULL when searching by GUID - entity-framework-4

I have a LINQ to Entities Query that is suppose to return a specific resultset based on the GUID provided.
[OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json)]
public List<OrderDetails> GetOrderDetailsByGUID(Guid OrderID)
{
var listit =(from OV in EC.OrderProductVariants
join O in EC.Orders on OV.OrderId equals O.Id
join PV in EC.ProductVariants on OV.ProductVariantId equals PV.Id
join P in EC.Products on PV.ProductId equals P.Id
join CT in EC.Customers on O.CustomerId equals CT.Id
join AD in EC.Addresses on CT.BillingAddress_Id equals AD.Id
where O.OrderGuid == OrderID
select new OrderDetails
{
OrderID = O.OrderGuid,
Company = AD.Company,
ShippingMethod = O.ShippingMethod,
Product = P.Name,
QuantityOnOrder = OV.Quantity
}
).ToList();
return listit;
}
It Returns NULL, can anyone tell me what I am doing wrong?

All solution that could work in a scenario like this is to create a view and do just a one liner code to access it
var q = EC.OrderProductVariants.SingleOrDefault(u => u.OrderGuid.Equals(guid));

Related

how return multiple column in join result to view model

I want to return multiple column in join result and fill in view model(VMFoodFoodMeal).
for example I want to fill VMFoodFoodMeal by Join result
Thanks
IEnumerable<VMFoodFoodMeal> _fmt = (from e in db.FoodProgramMealFood
join j in db.Foods on e.FoodId equals j.Id
select new
{
Id = e.Id,
Name = j.Name,
});
It is hard to understand what you want, but as example you can look here at Group Join section.
Here is an example code from there:
public void Linq103()
{
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = GetProductList();
var q =
from c in categories
join p in products on c equals p.Category into ps
select new { Category = c, Products = ps };
foreach (var v in q)
{
Console.WriteLine(v.Category + ":");
foreach (var p in v.Products)
{
Console.WriteLine(" " + p.ProductName);
}
}
}
result:
Beverages:
Chai
Chang
Guaraná Fantástica
Sasquatch Ale
Steeleye Stout
Côte de Blaye
Chartreuse verte
Ipoh Coffee
...
if you want to send your join Result to a model without using foreach statement you have to use this code
IEnumerable<VMFoodFoodMeal> _fmt = (from e in db.FoodProgramMealFood
join j in db.Foods on e.FoodId equals j.Id
select new VMFoodFoodMeal()
{
Id = e.Id,
Name = j.Name,
});
for example in above code I had a view model (VMFoodFoodMeal) and want to fill it by join result.
I have to make new instance of my model in select and then fill its property.
Thanks

pass a linq query with group by to view [errors out]

I got this in the controller
var tobi = (from a in db.Assessments
join u in db.Users on a.rated equals u.user_id
join tm in db.Team_Members on u.user_id equals tm.user_id
join t in db.Teams on tm.team_id equals t.team_id
where (tm.end_date == null || tm.end_date > DateTime.Today)
group new TobiViewModel
{
teamname = t.name,
assessed_due = a.assessed_due,
assessment_id = a.assessment_id,
rater = a.rater,
rated = a.rated
}
by new { t.name, a.rated }).ToList();
return View(tobi);
But then it doesn't accept it in the view?
The model item passed into the dictionary is of type
'System.Collections.Generic.List1[System.Linq.IGrouping2[<>f__AnonymousType102[System.String,System.String],Kyubu.ViewModels.TobiViewModel]]',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable1[Kyubu.ViewModels.TobiViewModel]'.
how should i pass this in the view. Any help would be appreciated
The type in the view is
#model IEnumerable<Kyubu.ViewModels.TobiViewModel>
Try the following in the view:
#model IEnumerable<System.Linq.IGrouping<object, Kyubu.ViewModels.TobiViewModel>>

Error in linq join query in MVC 4

I am trying this query:
public ActionResult Index()
{
var topics = from t in db.Topics
join subs in db.Subjects on t.SubID equals subs.SubID
join mems in db.Members on t.MemberID equals mems.MemberID
select new ViewModel
{
TopicID = t.TopicID,
TDate = t.TDate,
Title = t.Title,
FileName = t.FileName,
Displays = t.Displays,
Description = t.Description,
SubName = subs.SubName,
FLName = mems.FLName
};
return View(topics);
}
But it causes the following Error:
The entity or complex type 'MySiteModel.ViewModel' cannot be constructed in a LINQ to Entities query.
I have an Entitity Class with above fields.
What is the problem? ????
Try convert it to List<> first.
var topics = (from t in db.Topics
join subs in db.Subjects on t.SubID equals subs.SubID
join mems in db.Members on t.MemberID equals mems.MemberID
select new ViewModel
{
TopicID = t.TopicID,
TDate = t.TDate,
Title = t.Title,
FileName = t.FileName,
Displays = t.Displays,
Description = t.Description,
SubName = subs.SubName,
FLName = mems.FLName
}).ToList();
Hope it helps

LINQ convert DateTime to string

List<Post> list =
(
from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending
select new Post { Username = u.Username, PostingDate = c.Date.ToString(), Data = c.Comment }
).ToList();
The code above causes exception on the convertion of date to string, PostingDate = c.Date.ToString(). Any ideas how to get around this?
Exception error:
{"LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression."}
linq is trying to convert date to string using sql but since there is no ToString() method in sql it can't convert it, this behavior is by design - Joakim
In other words, return the date itself and convert it to a string after it executes on SQL side:
(
select new { Username = u.Username,
PostingDate = c.Date
[...]
})
.ToList() // runs on SQL and returns to the application
.Select(o => // is not generating a SQL, it is running on the app
new Post { Username = o.Username,
PostingDate = o.PostingDate.ToString(),
[...]
})
You can remedy your problem by projecting into an anonymous type, and then at a later step project into Post after the data has already been returned from the DB.
(from ....
select new { /* stuff */, Date = c.Date })
.AsEnumerable()
.Select(p => new Post { /* stuff */, PostingDate = p.Date.ToString() })
.ToList();
However, given that you have a property called PostingDate, the original source being a date, I would recommend your revise your object to actually keep the value as a DateTime instead of a string.
I dont think this can be done in a direct way.
var list =
select new Post { Username = u.Username, PostingDate = SqlFunctions.StringConvert(c.Date), Data = c.Comment }
from
(from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending).AsEnumerable()
).ToList();
Also with EF4 you can try something like this:
List<Post> list =
(
from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending
select new Post { Username = u.Username, PostingDate = SqlFunctions.DateName(c.Date), Data = c.Comment }
).ToList();

EF 4.0 Linq to Enity query

Hi guys i need to replicate this SQL query in Linq to Entity
select * from Subscriber a
inner join User b on a.UserId = b.Id
where b.Username = 'Name'
May be some one may help.
Try this:
var query = from s in context.Subscribers.Include("User")
where s.User.Username == "Name"
select s;
This suppose that Subscriber has navigation property User referencing the user instance.
If you wan to use join (which is not needed) you can use this for inner join:
var query = from s in context.Subscribers
join u in context.Users on s.User.Id equals u.Id
where u.Username == "Name"
select new
{
Subscriber = s,
User = u
};
or this for left outer join:
var query = from s in context.Subscribers
join u in context.Users on s.User.Id equals u.Id into x
where u.Username == "Name"
from y in x.DefaultIfEmpty()
select new
{
Subscriber = s
User = y,
};

Resources