can not addRange of items to var using linq and c# - linq

I have a following list of users:
var roles = userRoleRepository.Get(q => q.user_id.Equals(username, StringComparison.InvariantCultureIgnoreCase));
roles has two properties one is (ID,Name) ,how can i add a collection to this after i get the list?since roles,does not have add or addrange,i want to add("124","Jack")

It seems to me that UserRoleRepository is an object of one of your (company's) own classes. This class has a Get function that has some return value.
Alas you forgot to tell us the returned type. From the code snippet, I assume that the returned object is not a sequence of objects, but one single object, probably something that you'd call a UserRole. The returned UserRole is the one in the userRoleRepository that has a user_id that equals some string userName.
As the Get function returns only one UserRole it is not a meaningful action to add a collection to this one object, unless this UserRole has a function to add a collection. But as you told us: your UserRole does not have such a function.
Or are you a bit sloppy in your description and do you want to add some UserRoles to the collection of UserRoles that would be the return of your Get function? Alas again: you didn't give us a definition of the return value of your Get function.
If Get returns one UserRole and you want the combination of this fetched UserRole together with your own sequence of UserRoles, do the following:
UserRole fetchedUserRole = userRoleRepository.Get(...);
List<UserRole> userRoles = new List<UserRole>();
userRoles.Add(fetchedUserRole);
return userRoles.Concat(myOwnUserRoleCollection);
If on the other hand Get returns a sequence of USerRole, the code would be even simpler:
IEnumerable<UserRole> fetchedUserRoles = userRoleRepository.Get(...);
return fetchedUserRoles.Concat(myOwnUserRoleCollection);

Related

Spring Open Projection - Object and Additional Value

Let's assume we have a model like this:
class User {
String name;
Integer age;
}
The query returns results, and the extraField is mapped, but the user isn't.
I have a query that joins the User table with another table and returns the User object and one more field that comes from this other table.
Is it possible to define an open projection in Spring that would map the return values from the query? I guess it should look something like the following, but I can't get it to work.
interface UserProjection {
User getUser();
#Value("#{target.extrafield}")
String getExtraField();
}

converting from linq var result to another object

using the following LINQ query I want 'chosen' to be a 'User' object which I know and can manipulate, but it's not. How can I convert it to 'User'?
Thanks
Console.Write("User name:");
String nickname = Console.ReadLine();
var loggedin = from user in userList
where user.getNickname().Equals(nickname)
select user;
Currently, your query returns an IEnumerable<T> where T is the type of elements in userList.
It seems like you're after the FirstOrDefault eager operation to retrieve only a single User object if present.
var loggedin = (from user in userList
where user.getNickname().Equals(nickname)
select user).FirstOrDefault();
loggedin will be null if userList is empty, or if there is no element satisfying the provided predicate.
Using method syntax the same can be accomplished like this:
var loggedin = userList.FirstOrDefault(user => user.getNickname().Equals(nickname));

Check if User object exists in #DBRef List<User>

I'm making use of MongoDB, Spring Data and Spring MVC.
I have a user model which has a list of contacts:
class User {
#DBRef
private List<User> contacts = new ArrayList<User>();
public List<User> getContacts() {
return contacts;
}
}
I currently have 4 users inside my database. 1 user has a particular contact (who is referred to the same collection by id).
Now, I want to check whether a user has a particular contact. I use the following code:
User userLoggedIn = userService.getLoggedInUser(); //user object
User contact = userService.findById(contactId); //contact
if(userLoggedIn.getContacts().contains(contact)) {
System.out.println("Has this contact.");
}
This output message is not shown. However, if I print the list of contacts of the user and their id's, I clearly see that the contact is inserted inside the list of the user.
I noticed that if I print the hashCode of the contact object and the one that is inside the list, I get a different value, so I assume that even though the details are the same, the object itself isn't.
How can I approach this problem by simply checking whether he is inside the list. Or should I just compare by id?
Otherwise stated: how can I check whether an object exists in the contacts list?
You should override an equals method in User.
From JavaDoc:
boolean contains(Object o)
Returns true if this list contains the specified element. More
formally, returns true if and only if this list contains at least one
element e such that (o==null ? e==null : o.equals(e)).
With equals you must override and hashCode
http://docs.jboss.org/hibernate/core/4.0/manual/en-US/html/persistent-classes.html#persistent-classes-equalshashcode

How can I create a LINQ view?

My team is using Entity Framework 4.3.0 - Code Only with POCO classes as our ORM. Right now we use DBSets of Classes to access our 'tables'
Public Property Customers As DbSet(Of Customers)
But often we are doing soft deletes based on a IsDeleted column in LINQ, and filtering our select statements accordingly:
Dim LiveCustomers =
From C In EM.Customers
Where C.DeleteFlag = False
What I would really like to do is, instead of writing every query to include this filter, create some lower level property (possibly at our inherited DbContext level) that provides the filtered set, while maintaining strong type.
I tried this:
Public Property Customers As DbSet(Of Customer)
Public Property Customers_Live As DbSet(Of Customer)
Get
Return From C In Customers
Where C.DeleteFlag = False
End Get
Set(value As DbSet(Of Customer))
Customers = value
End Set
End Property
However that yielded me this error:
Multiple object sets per type are not supported. The object sets 'Customers' and 'Customers_Live' can both contain instances of type '__.Customer'.
A quick check on google yielded this promising result (How to: Query Objects with Multiple Entity Sets per Type) But after updating my Connection String, I'm still getting the same error.
<add name="EntityManager"
providerName="System.Data.SqlClient"
connectionString="
Data Source=xxxxxx;
Initial Catalog=xxxxxx;
User Id=xxxxxx;
Password=xxxxxx;
MultipleActiveResultSets=True"/>
So my question is, how could I effectively create a LINQ view that allows me to apply filtering, without impacting the upstream usage too drastically?
Change your property like this:
Public Property Customers As DbSet(Of Customer)
Public Property Customers_Live As IQueryable(Of Customer)
Get
Return From C In Customers
Where C.DeleteFlag = False
End Get
End Property
This is slightly different, as you won't have things like Add() or Remove(), but for a view you typically wouldn't expect to have that kind of functionality. If you want to add a new one, or remove one you should use the normal Customers property.
You could have your POCO classes inherit from a new class that has a new method that would do the filtering for you. Add something like this to the new class
--PSEUDO CODE!--
Public Function Filtered() as IEnumerable(Of Out T)
Return (From x In Me Where x.DeleteFlag).ToList()
End Function
and you could call it like:
Dim LiveCustomers =
From C In EM.Customers.Filtered
Or you could create an Interface and do a dependancy injection when you call your linq query. You'll have to google that one :)

How do you re-use select statements with Entity Framework?

Given the following query:
var query = from item in context.Users // Users if of type TblUser
select new User() // User is the domain class model
{
ID = item.Username,
Username = item.Username
};
How can I re-use the select part of the statement in other queries? I.e.
var query = from item in context.Jobs // Jobs if of type TblJob
select new Job() // Job is the domain class model
{
ID = item.JobId,
User = ReuseAboveSelectStatement(item.User);
};
I tried just using a mapper method:
public User MapUser(TblUser item)
{
return item == null ? null : new User()
{
ID = item.UserId,
Username = item.Username
};
}
With:
var query = from item in context.Users // Users if of type TblUser
select MapUser(item);
But if I do this, then the framework throws an error such as:
LINQ to Entities does not recognize
the method 'MapUser(TblUser)' method,
and this method cannot be translated
into a store expression.
You can't use regular function calls in a query definition like that. LINQ needs expression trees, it can't analyze compiled functions and magically translate that to SQL. Read this for a more elaborate explanation
The techniques used in the cited article are incorporated in linqkit (factoring out predicates) and might be of help, though I'm not sure you can use the same technique for managing projections, which is what you seem to want.
The more fundamental question you should ask yourself here IMHO is whether you really need this extra mapping layer? It seems like you're implementing something that EF is already perfectly capable of doing for you...
Try making your MapUser method static.

Resources