I'm trying to get eager loading working with Subsonic, and it's been returning null for me.
In the method below, I'm trying to hydrate a domain model (UserModel) which contains another domain model (CompanyModel). However, with the code below, UserModel.Company is always null.
What am I missing here. Any help would be appreciated.
public IList<UserModel> GetUsers()
{
return (from u in SubsonicSqlServer.Users.All()
select new UserModel
{
UserId= u.UserId,
Company = (from c in u.Companies
select new CompanyModel
{
CompanyId = c.CompanyId,
CompanyName = c.CompanyName
}).SingleOrDefault(),
FirstName = u.FirstName,
LastName = u.LastName,
BirthDate = u.BirthDate
}).ToList();
}
Update (08/11/09):
More toying around with the code, I found out that setting CompanyId in the following example doesn't work either. I initially thought this was an issue with Subsonic, but if the code below doesn't work, I'm guessing it has something to do with my Linq statement. Any ideas?
public IList<UserModel> GetUsers()
{
return (from u in SubsonicSqlServer.Users.All()
select new UserModel
{
UserId= u.UserId,
CompanyId = Guid.NewGuid(),
FirstName = u.FirstName,
LastName = u.LastName,
BirthDate = u.BirthDate
}).ToList();
}
Update (11/17/2009):
Still haven't found a solution. But we are switching to nHibernate (not because of this issue).
"UserModel.Company is always null."
since you are setting this with an expression that ends with .SingleOrDefault(), I'm going to suggest that the query isn't returning a single item. Start investigating there. If you are expecting exactly one item in u.Companies, change to .Single() and force an early failure.
You can do the .Single() before creating the new CompanyModel object, I think.
As for style, I like the query comprehension syntax ("from x in y select") but find it awkward when combined with traditional dot-notation syntax. It's just hard to read. (LINQ - Fluent and Query Expression - Is there any benefit(s) of one over other?).
Consider using let in the query comprehension to make it clearer.
Also, since a query already returns an IEnumerable<T>, and calling ToList() forces all items to be realized, I would modify my method to return IEnumerable<T> if possible.
So, in your case, I would refactor the first to say:
public IEnumerable<User> GetUsers()
{
return from u in SubsonicSqlServer.Users.All()
let c = u.Companies.Single()
select new UserModel
{
UserId = u.UserId,
Company = new CompanyModel
{
CompanyId = c.CompanyId,
CompanyName = c.CompanyName
},
FirstName = e.FirstName,
LastName = e.LastName,
BirthDate = e.BirthDate
};
}
If it makes sense in your object model, you could modify User to have a constructor that takes whatever type u is, and it gets even simpler:
return from u in SubsonicSqlServer.Users.All()
select new UserModel (u);
or even
return SubsonicSqlServer.Users.All().Select(u => new UserModel (u));
Two things
You're returning a List<UserModel> when your method's signature line says IList<User> does UserModel inherit from User?
Am I missing something, where does e come from?
FirstName = e.FirstName,
LastName = e.LastName,
BirthDate = e.BirthDate Blockquote
Please check out my fork # github (http://github.com/funky81/SubSonic-3.0/commit/aa7a9c1b564b2667db7fbd41e09ab72f5d58dcdb) for this solution, actually there's a problem when subsonic try to project new type class, so there's nothin wrong with your code actually :D
Related
I currently have a LINQ query written in one my controllers that I want to return a single blog post (based off a model) with corresponding comments and topics.
This is what I currently have as my query which I used to return a list of all my blog posts for the home page. I added "where p.id == id (which is the parameter taken in by the ActionResult to fetch the correct post.
var post = from p in db.Set<BlogPost>()
where p.id == id
select new PostViewModel
{
Id = p.id,
Title = p.Title,
DateCreated = p.DateCreated,
Content = p.Content,
Topics = p.Topics,
Comments = p.Comments,
CommentCount = p.Comments.Count
};
return View(post);
The return currently is sending an IQueryable when I just want it to be a single post. Currently I have a foreach in my razor view which is useless and wrong but it works. How can I change this to do what I want?
You can do:
return View(post.SingleOrDefault());
Or if you want to have an exception in the case list is empty:
return View(post.Single());
Just add First() or Single() (which one is right for you depends on context) to your query:
return View(post.First());
It sound like you want to use First or Single:
return View(post.Single());
The difference between them is that Single will throw an exception if more than one matching row is found.
Just do post.First() that should do the trick. Really any function that produces a concrete value will work. First, FirstOrDefault, Single, SingleOrDefault, ToList, or ToArray
I have included the links to each method so you can see what works for you. It sounds like you will want a First or Single variation, depending on if you want errors if more than one post is pulled
replace your LINQ with this
var post = (from p in db.Set<BlogPost>()
where p.id == id
select new PostViewModel
{
Id = p.id,
Title = p.Title,
DateCreated = p.DateCreated,
Content = p.Content,
Topics = p.Topics,
Comments = p.Comments,
CommentCount = p.Comments.Count
}).FirstOrDefault();
I have spent hours upon hours trying to figure out how to shape the data projected from linq to a strongly type view. My problem is I think my problem is I am unsure how to use IEnumberable and IGrouping.
Here is the linq:
var spec = from a in _entities.Approvals
join b in _entities.ApprovalSpecifications on a.HeaderlID equals b.HeaderlID into g
where a.ApprovalID == id
group a by a.HeaderlID into groupedByHeader
select new
{
Key = groupedByHeader.Key,
groupedByHeader
};
Can anyone suggest the method with which I should approach this? I am thinking a class for this would work best, but as I mentioned I'm not sure how to use IGrouping to build a class. Any help is appreciated!
Something like this?
class StronglyTypedGrouping {
public object Key { get; set; } // I can't infer Key type from the snippet.
public IEnumerable<Approval> Approvals { get; set; }
}
var spec = from a in _entities.Approvals
join b in _entities.ApprovalSpecifications on
a.HeaderlID equals b.HeaderlID into g
where a.ApprovalID == id
group a by a.HeaderlID into groupedByHeader
select new StronglyTypedGrouping {
Key = groupedByHeader.Key,
Approvals = groupedByHeader
};
OK I'm banging my head against a wall with this one ;-)
Given tables in my database called Address, Customer and CustomerType, I want to display combined summary information about the customer so I create a query to join these two tables and retrieve a specified result.
var customers = (from c in tblCustomer.All()
join address in tblAddress.All() on c.Address equals address.AddressId
join type in tblCustomerType.All() on c.CustomerType equals type.CustomerTypeId
select new CustomerSummaryView
{
CustomerName = c.CustomerName,
CustomerType = type.Description,
Postcode = address.Postcode
});
return View(customers);
CustomerSummaryView is a simple POCO
public class CustomerSummaryView
{
public string Postcode { get; set; }
public string CustomerType { get; set; }
public string CustomerName { get; set; }
}
Now for some reason, this doesn't work, I get an IEnumerable list of CustomerSummaryView results, each record has a customer name and a postcode but the customer type field is always null.
I've recreated this problem several times with different database tables, and projected classes.
Anyone any ideas?
I can't repro this issue - here's a test I just tried:
[Fact]
public void Joined_Projection_Should_Return_All_Values() {
var qry = (from c in _db.Customers
join order in _db.Orders on c.CustomerID equals order.CustomerID
join details in _db.OrderDetails on order.OrderID equals details.OrderID
join products in _db.Products on details.ProductID equals products.ProductID
select new CustomerSummaryView
{
CustomerID = c.CustomerID,
OrderID = order.OrderID,
ProductName = products.ProductName
});
Assert.True(qry.Count() > 0);
foreach (var view in qry) {
Assert.False(String.IsNullOrEmpty(view.ProductName));
Assert.True(view.OrderID > 0);
Assert.False(String.IsNullOrEmpty(view.CustomerID));
}
}
This passed perfectly. I'm wondering if you're using a reserved word in there?
This post seems to be referring to a similar issue...
http://groups.google.com/group/subsonicproject/browse_thread/thread/2b569539b7f67a34?hl=en&pli=1
Yes, the reason Rob's example works is because his projection's property names match exactly, whereas John's original example has a difference between CustomerType and type.Description.
This shouldn't have been a problem, but it was - the Projection Mapper was looking for properties of the same name and wasn't mapping a value if it didn't find a match. Therefore, your projection objects' properties would be default values for its type if there wasn't an exact name match.
The good news is, I got the latest source today and built a new Subsonic.Core.dll and the behavior is now fixed.
So John's code above should work as expected.
I just downloaded the latest build from 3/21/2010, which is about 2 months after the last poster on this thread, and the problem still exists in the packaged binary. Bummer.
Here what I have to do:
var data =
(from m in Metric.All()
where m.ParentMetricId == parentId
select new
{
m.MetricName,
m.MetricId,
})
.ToList();
var treeData =
from d in data
select new TreeViewItem
{
Text = d.MetricName,
Value = d.MetricId.ToString(),
LoadOnDemand = true,
Enabled = true,
};
return new JsonResult { Data = treeData };
If I try to do the projection directly from the Subsonic query, the Text property ends up with the ID, and the Value property ends up with the Name. Very strange.
So I'm new to linq so be warned what I'm doing may be completely stupid!
I've got a table of caseStudies and a table of Services with a many to many relasionship
the case studies already exist and I'm trying to insert a service whilst linking some case studies that already exist to it. I was presuming something like this would work?
Service service = new Service()
{
CreateDate = DateTime.Now,
CreatedBy = (from u in db.Users
where u.Id == userId
select u).Take(1).First(),
Description = description,
Title = title,
CaseStudies = (from c in db.CaseStudies
where c.Name == caseStudy
select c),
Icon = iconFile,
FeatureImageGroupId = imgGroupId,
UpdateDate = DateTime.Now,
UpdatedBy = (from u in db.Users
where u.Id == userId
select u).Take(1).First()
};
But This isn't correct as it complains about
Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Data.Objects.DataClasses.EntityCollection'
Can somebody please show me the correct way.
Thanks in advance
Yo have to add the query result to the case studies collection instead of trying to replace it.
var service = new Service { ... };
foreach (var caseStudy in db.CaseStudies.Where(s => s.Name == caseStudyName)
{
service.CaseStudies.Add(caseStudy);
}
You can wrap this in an extension method and get a nice syntax.
public static class ExtensionMethods
{
public static void AddRange<T>(this EntityCollection<T> entityCollection,
IEnumerable<T> entities)
{
// Add sanity checks here.
foreach (T entity in entities)
{
entityCollection.Add(entity);
}
}
}
And now you get the following.
var service = new Service { ... };
service.CaseStudies.AddRange(db.CaseStudies.Where(s => s.Name == caseStudyName));
how come this work
public IQueryable<Category> getCategories(int postId)
{
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
var query = from c in categories.GetAll()
join pcm in postCategoryMap.GetAll() on c.CategoryId equals pcm.CategoryId
where pcm.PostId == 1
select new Category
{
Name = c.Name,
CategoryId = c.CategoryId
};
return query;
}
but this does not
public IQueryable<Category> getCategories(int postId)
{
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
var query = from c in categories.GetAll()
join pcm in postCategoryMap.GetAll() on c.CategoryId equals pcm.CategoryId
where pcm.PostId == postId
select new Category
{
Name = c.Name,
CategoryId = c.CategoryId
};
return query;
}
The issue is most likely in the implementation of the query provider.
pcm.PostId == 1
and
pcm.PostId == postId
actually have a big difference. In the expression tree the first is generated as a ConstantExpression which doesnt need to be evaulated.
With the second, the compiler actually generates an inner class here (this is the _DisplayClassX that you see). This class will have a property (will most likely be the same name as your parameter) and the expression tree will create a MemberAccessExpression which points to the auto-generated DisplayClassX. When you query provider comes accross this you need to Compile() the Lambda expression and evaluate the delegate to get the value to use in your query.
Hope this helps.
cosullivan
The problem is not the linq itself,
you need to be sure that the context or provider object is able to fetch the data.
try testing the
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
objects and see if they are populated or if they behaving as required.
you may want to search the generated code for c__DisplayClass1 and see what you can see there. some times the generated code dose some weird things.
when you step into you code check the locals and the variable values. this may also give you some clues.
Edit : Have you tried to return a List<> collection ? or an Enumerable type?
Edit : What is the real type of the item and query may not be iterable