Display a specific data for User - asp.net-mvc-3

I have a problem similar to this topic http://forums.asp.net/t/1763534.aspx/1
I have to show data to customers based on their username. I do not create a new topic because I've done that long ago and nobody has responded. I ask you because you seem to know it more than others ...
This is my controller
public ActionResult Index()
{
MembershipUser currentUser =
Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
ViewBag.UsersRecord = currentUser.ProviderUserKey;
var details = from t in db.Employes
where t.UserId ==ViewBag.UsersRecord
select t;
return View(details.ToList());
}
Strangely, Visual Studio shows me an error here
where t.UserId == ViewBag.UsersRecord
"An expression tree may not Contain dinamyc in operation"
I've done something wrong?

You can't use dynamic, since dynamic is determined at compile time.
try:
Guid userId = (Guid)ViewBag.UsersRecord;
var details = from t in db.Employes
where t.UserId == userId.ToString() //if you are using a string guid, otherwise remove ToString()
select t;
//or simply
var details = from t in db.Employes
where t.UserId == (Guid)currentUser.ProviderUserKey
select t;
I don't know what your UserId is (type wise) so can't give you a 100% answer here

What about this:
where t.UserId == new Guid(ViewBag.UsersRecord.ToString());

Related

LINQ Query returning IQueryable, need it to be a single result

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();

Linq Query for Complex Object

Everyone - I have the following set of objects:
User { String:Name, List<Devices> }
Device {String:Name, DeviceVariationInfo }
DeviceVariationInfo { String:OS }
In the database those object are split into the following tables:
Users, Devices, DevieVariationsInfo, UserToDevices
I am trying to query the the list of devices along with their variation info for a certain user, and am using the following query, which always returns a list of 0 items in Devices. I am pretty sure I am doing something wrong here.. =)
private void GetUserDevices(ref User user)
{
User locUSer = user;
if (user != null)
{
var deviesQuery = from dts in _dataConext.DB_UserToDevices
where dts.UserId == locUSer.Id
join ds in _dataConext.DB_Devices on dts.DeviceID equals ds.Id
join dsv in _dataConext.DB_DeviceVariations on ds.Id equals dsv.DeviceId
select new Device
{
Version = ds.Version,
VariationInfo = new DeviceVariation
{
OSVersion = dsv.OS
},
Name = ds.FriendlyName,
Id = ds.Id
};
if (deviesQuery != null)
user.Devices = deviesQuery.ToList();
}
}
A couple of notes:
Is User a class? If so, why are you passing it into GetUserDevices by ref? Don't do that unless you want to change the meaning of that reference.
Also, why are you doing this? User locUSer = user;
Here's how I'd go about debugging your problem: remove parts of that query until you get data back. For example, remove the last join statement, rerun the query, and see where you're going wrong.

Linq nested select new not working

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

Linq one to many insert when many already exists

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));

linq help - newbie

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

Resources