Get All users with UserRoleID - apex-code

I am trying to fetch all users of a role and add their email into a string[] i have some syntax.
Error:"common.apex.runtime.impl.ExecutionException: Attempt to de-reference a null object"|0x2f253344
My Code.
String[] s;
for (User a : [Select id,name,email from User where UserRoleId = '00E90000000dffgEAA']) {
s.add(a.email);
}

The list of strings should be initialized by an empty list. It was easy.
String[] s = new String[] {};

I think, it is giving error, because your soql query is not returning any rows.
You can do something like this to get rid of errors...
Integer number_of_rows = [Select id,name,email from User where UserRoleId = '00E90000000dffgEAA'];
if(number_of_rows>0)
{
String[] s;
for (User a : [Select id,name,email from User where UserRoleId = '00E90000000dffgEAA']) {
s.add(a.email);
}
}

Related

LINQ perform select and insert in single query

I am working on Entity Framework 6 in C# .NET CORE 2.0 application. I have requirement to get role id from database where roleName = x and add role reference to user as in one: many table
I want to avoid 2 trip to database, I want to do in one go or in single Linq query
UserDataModel userObj = new UserDataModel()
{
Id = fakeUserID,
Name = "k1",
Surname = "z",
Email = "k.z#yahoo.co.uk",
Roles = new List<UserRoleDataModel>
{
new UserRoleDataModel {
UserId = fakeUserID,
RoleId = Context.Roles.Where(roleName => roleName.Name == RoleName).Select(x=>x.Id)
}
}
};
Context.Add<UserModel>(userObj);
Context.SaveChanges();
above code gives me error at RoleId
refer in screen shot;
Error because you are assigning IQueryable to a Property of type Int (I Assumed its Int). You should do this:
RoleId = Context.Roles.Where(roleName => roleName.Name == RoleName && roleName.Id==Id).Select(x=>x.Id).First();

Associate user when created with an existing Account

I have a code that checks an inquery database a for user,
If the user does not exist, then the code will create a new user in Contact,
Here is only part of the code:
newcontact = [SELECT Id, FirstName FROM Contact WHERE Contact.Email =inquery.email__c];
if(newcontact.size() == 0) {
Account[] aa = [SELECT Id FROM Account WHERE Name = :inquery.Institution__c];
contact = new Contact();
contact.FirstName = inquery.First_Name__c;
contact.LastName = inquery.Last_Name__c;
contact.Email = inquery.email__c;
contact.AccountId = aa.Id;
try {
insert contact; // inserts the new record into the database
} catch (DMLException e) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error creating new contact'));
return null;
}
I am trying to associate that user with an existing Account?
But the following line gives me an error:
contact.AccountId = aa.Id;
Which is
Initial term of field expression must be a concrete SObject: LIST<Account> at line
And aa.size() returns 1, as it should,
Because the account exists,
Can someone please tell me what wrong?
Thanks
This line contact.AccountId = aa.get(0).Id; will fail if your query returns 0 rows. Make sure to wrap your code within a if (aa.size() > 0) clause to ensure proper execution in all cases.
Ok I fixed it, as follows:
contact.AccountId = aa.get(0).Id;
Best

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.

Only primitive types ('such as Int32, String, and Guid') are supported in this context when I try updating my viewmodel

I am having some trouble with a linq query I am trying to write.
I am trying to use the repository pattern without to much luck. Basically I have a list of transactions and a 2nd list which contains the description field that maps against a field in my case StoreItemID
public static IList<TransactionViewModel> All()
{
var result = (IList<TransactionViewModel>)HttpContext.Current.Session["Transactions"];
if (result == null)
{
var rewardTypes = BusinessItemRepository.GetItemTypes(StoreID);
HttpContext.Current.Session["Transactions"] =
result =
(from item in new MyEntities().TransactionEntries
select new TransactionViewModel()
{
ItemDescription = itemTypes.FirstOrDefault(r=>r.StoreItemID==item.StoreItemID).ItemDescription,
TransactionDate = item.PurchaseDate.Value,
TransactionAmount = item.TransactionAmount.Value,
}).ToList();
}
return result;
}
public static List<BusinessItemViewModel>GetItemTypes(int storeID)
{
var result = (List<BusinessItemViewModel>)HttpContext.Current.Session["ItemTypes"];
if (result == null)
{
HttpContext.Current.Session["ItemTypes"] = result =
(from items in new MyEntities().StoreItems
where items.IsDeleted == false && items.StoreID == storeID
select new BusinessItemViewModel()
{
ItemDescription = items.Description,
StoreID = items.StoreID,
StoreItemID = items.StoreItemID
}).ToList();
}
return result;
However I get this error
Unable to create a constant value of type 'MyMVC.ViewModels.BusinessItemViewModel'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
I know its this line of code as if I comment it out it works ok
ItemDescription = itemTypes.FirstOrDefault(r=>r.StoreItemID==item.StoreItemID).ItemDescription,
How can I map ItemDescription against my list of itemTypes?
Any help would be great :)
This line has a problem:
ItemDescription = itemTypes.FirstOrDefault(r=>r.StoreItemID==item.StoreItemID)
.ItemDescription,
Since you are using FirstOrDefault you will get null as default value for a reference type if there is no item that satifies the condition, then you'd get an exception when trying to access ItemDescription - either use First() if there always will be at least one match or check and define a default property value for ItemDescription to use if there is none:
ItemDescription = itemTypes.Any(r=>r.StoreItemID==item.StoreItemID)
? itemTypes.First(r=>r.StoreItemID==item.StoreItemID)
.ItemDescription
: "My Default",
If itemTypes is IEnumerable then it can't be used in your query (which is what the error message is telling you), because the query provider doesn't know what to do with it. So assuming the that itemTypes is based on a table in the same db as TransactionEntities, then you can use a join to achieve the same goal:
using (var entities = new MyEntities())
{
HttpContext.Current.Session["Transactions"] = result =
(from item in new entities.TransactionEntries
join itemType in entities.ItemTypes on item.StoreItemID equals itemType.StoreItemID
select new TransactionViewModel()
{
ItemDescription = itemType.ItemDescription,
TransactionDate = item.PurchaseDate.Value,
TransactionAmount = item.TransactionAmount.Value,
CustomerName = rewards.CardID//TODO: Get customer name
}).ToList();
}
I don't know the structure of your database, but hopefully you get the idea.
I had this error due a nullable integer in my LINQ query.
Adding a check within my query it solved my problem.
query with problem:
var x = entities.MyObjects.FirstOrDefault(s => s.Obj_Id.Equals(y.OBJ_ID));
query with problem solved:
var x = entities.MyObjects.FirstOrDefault(s => s.Obj_Id.HasValue && s.Obj_Id.Value.Equals(y.OBJ_ID));

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

Resources