Associate user when created with an existing Account - apex-code

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

Related

Creating a Salesforce Apex Trigger to update a lookup field in the Contacts object

I have created a trigger that will auto-create a contact when a specific Account record type is created or updated. The problem is that I am not sure how to populate the Contact 'Account Name' lookup field. This field is a lookup to the Account object. My code is below. Any help on how to integrate this missing component would be greatly appreciated.
trigger autoCreateContact on Account (after update, after insert)
{
List newContact = new List();
for (Account oAccount : trigger.new)
{
if (oAccount.RecordTypeid == '012F0000001MCfgIAG')
{
List<Contact> cCheck = [SELECT ID From Contact WHERE LastName=:oAccount.Name];
if(cCheck.isEmpty()==True)
{
System.debug(oAccount);
Contact oContact = new Contact();
oContact.LastName = oAccount.Name;
oContact.phone = oAccount.Phone;
oContact.email = oAccount.Email__c;
oContact.Owner = oAccount.Owner;
newContact.add(oContact);
}
}
if(newContact.isEmpty() == false)
{
Database.insert(newContact);
}
}
}
nice trigger I'm pretty sure you just need to add one line which is a reference to the account.id.
So if I were you I would add the link:
oContact.AccountID = oAccount.id;
NOTE: its not a good practice to have a SOQL inside the for loop.

mvc3 assign anonymous types or workaround

I have a model that is used to modify a user's password and captures the date that the password has been changed. I am getting an error saying property or indexer anonymous type cannot be assigned to it is read only I get that error for both fields the password and CreateDate . I only know of 1 way to select multiple fields from entity and this is it..
var old= db.registration.Where(b => b.email == getid.email).Select
(s => new { s.password, s.CreateDate }).FirstOrDefault();
old.CreateDate = DateTime.Now();
old.password = new.password;
db.Entry(old).State = EntityState.Modified;
db.SaveChanges();
Is there a way that I can assign these new values without getting the error message or a workaround ?
Just select the default object and run with it
var old= db.registration.Where(b => b.email == getid.email).FirstOrDefault();
old.CreateDate = DateTime.Now();
old.password = new.password;
db.Entry(old).State = EntityState.Modified;
db.SaveChanges();
The error message you're getting is likely because you're assigning to the index of an anonymous type, ie.
s => new { s.password, s.CreateDate }
is anonymous and its indexed properties cant be assigned to

why EF tries to add new record instead of edit?

I have the following code:
var currentUser = (from i in _dbContext.Users
where i.FirstName == user.FirstName && i.LastName == user.LastName
&& i.Title == user.Title && i.Company == user.Company
select i).FirstOrDefault();
currentUser.Company = user.Company;
currentUser.CompanyUrl = user.CompanyUrl;
currentUser.Country = user.Country;
_dbContext.SaveChanges();
but I got an error
{"Violation of UNIQUE KEY constraint 'IX_Users'. Cannot insert
duplicate key in object 'dbo.Users'. The duplicate key value is (a8,
b8, c8).\r\nThe statement has been terminated."}
so, it says that EF tries to add new record instead of edit current. Why?
I think the problem will be combining user and currentUser. It most probably updates your currentUser but in the same time inserts user. The reason can be this:
currentUser.Company = user.Company;
If company has Users navigation property and if you are using POCO template this will connect both Company and user as new entities to the context.
Try this:
var currentUser = ...;
var company = new Company { Id = user.Company.Id };
_dbContext.Companies.Attach(company);
currentUser.Company = company;
...
_dbContext.SaveChanges();

Display a specific data for User

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

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.

Resources