I have this piece of example code:
public Post findById(Long id) {
String sql = "select id, title, text from post where id = ?";
return template.queryForObject(sql, new Object[] {id}, getPostRowMapper());
}
I don't understand what the new Object[] {id} is doing here
When you have a sql statement with a variable in it (the question mark sign), then you need to supply the variables that will be placed into that statement where the question marks are.
new Object[] {id} tells us which variables should be put in places where the question marks are.
new Object[] {} creates an empty array of objects. new Object[] {id} creates an array of objects with one item in it - the Long id, which is the function parameter.
So, let's say id is equal to 1. In that case, the question mark
where id = ?
Will be replaced with 1
where id = 1
Related
I am quite new to entity framework and linq but basically I am using data first and my database has a table called tblNumbers and it has 2 columns, an id column and a numbers column which is populated with int values, I want to populate only the number values into my list but when I try do this I get an error saying that I cannot implicitly convert system.collections.generic.list< int> to system.collections.generic.list<projectname.Models.tblNumber>. I am not sure where to go from this, any help would be much appreciated.
Here is my code:
private DatabaseEntities db = new DatabaseEntities();
public ActionResult MyAction()
{
db.Configuration.ProxyCreationEnabled = false;
List<tblNumber> numbers = db.tblNumbers.Select(column => column.numbers).ToList();
return View();
}
Your List<tblNumber> numbers is expecting a list of tblNumber type and you are selecting column.numbers only
var numbers = db.tblNumbers.Select(column => column.numbers).ToList();
Hey I am working with nested maps as I was trying to use nested map I initialized this map>>. I need to pass accounts industry at key and need to show number of account and accounts group by industry
I have tried to put value but it is showing null pointer exception
Apex class
public class Map_Practice_Show_Account_industry {
public static void mapindustry(){
Map<String,Map<Integer,List<Account>>> m = new Map<String,Map<Integer,List<Account>>>();
List<Account> lstacc = [SELECT Id, Name, Industry FROM Account WHERE industry != Null ];
for(Account acc : lstacc){
List<Account> lstacc1 = new List<Account>();
lstacc1.add(acc);
if(m.containsKey(acc.Industry)){
m.get(acc.Industry).put(m.get(acc.Industry).size(),lstacc1);
} else {
Map<Integer, List<Account>> macc=new Map<Integer, List<Account>>();
macc.put(m.get(acc.Industry).size(),new List<Account>{acc});
m.put(acc.Industry, macc);
}
}
System.debug('#### : '+ m.get('Agriculture'));
}
}
I need to show result like agriculture as a key and at integer 2 and its accounts name
Your error is in second line of you else part (follow pointer for error)
public class Map_Practice_Show_Account_industry {
public static void mapindustry(){
Map<String,Map<Integer,List<Account>>> m = new Map<String,Map<Integer,List<Account>>>();
List<Account> lstacc = [SELECT Id, Name, Industry FROM Account WHERE industry != Null ];
for(Account acc : lstacc){
List<Account> lstacc1 = new List<Account>();
lstacc1.add(acc);
if(m.containsKey(acc.Industry)){
m.get(acc.Industry).put(m.get(acc.Industry).size(),lstacc1);
} else {
Map<Integer, List<Account>> macc=new Map<Integer, List<Account>>();
-->macc.put(m.get(acc.Industry).size(),new List<Account>{acc});
m.put(acc.Industry, macc);
}
}
System.debug('#### : '+ m.get('Agriculture'));
}
}
In if part you are checking if your map contains key acc.Industry but in else part you are still trying to access it even when it's not present in map, it is returning null as a result. Calling size() method on a null object will lead to Null Pointer exception.
Edit:-
then what would be the solution to get the desire result as i am not
able to get size of no of account
I think you have unnecessarily complicated this code. From what I understand from your problem statement, you only need a Map<String, List<Account>> with industry as key and related list of accounts as value. You can get size of accounts for particular industry by fetching list of accounts for that industry and then calling size method on that list. Here is code for this scenario
public class AccountUtils {
//Get all accounts with Industry as key and List of Accounts as Value
public static Map<String,List<Account>> getAccountsGroupedByIndustryMap(){
Map<String,List<Account>> accountsGroupedByIndustry = new Map<String,List<Account>>();
//Fetch all accounts with Industry
List<Account> accountsWithIndustry = [SELECT Id, Name, Industry FROM Account WHERE Industry <> NULL];
for(Account acc : accountsWithIndustry){
List<Account> accountList;
//Check if map already contains current Industry as key
if(accountsGroupedByIndustry.containsKey(acc.Industry)){
//Fetch existing list, add new value and put it back in map
accountList = accountsGroupedByIndustry.get(acc.Industry);
accountList.add(acc);
} else {//If key doesn't exist, create a new list and add account value
accountList = new List<Account>();
accountList.add(acc);
}
//Finally put this list in the map with Industry as key
accountsGroupedByIndustry.put(acc.Industry,accountList);
}
return accountsGroupedByIndustry;
}
}
Posting this from my cellphone not sure how formatting will look like if someone can edit :)
Like pointed above your error is in your second line of the else statement. You are trying to get the size that the industry key is pointing at BEFORE the industry type is inserted to map. Getting non existing keys returns a null and you're trying to get the size() of the null.
So to anwer you're question: Just hardcode the key as ZERO since it's the first elemnent.
Before
macc.put(m.get(acc.Industry).size(),new List<Account>{acc});
After
macc.put(0,new List<Account>{acc});
I am retrieving the contents of a database using a object (its returning only one field) and then comparing it with a string which has been hashed with SHA1 .The code is as follows :
protected void Onbutton_click_login(object sender, System.EventArgs e)
{
var dbcontext = new PrepLicensingSolution2010.DAL.LicensingEntities1();
var user = dbcontext.getloginname(loginName.Text);
string HashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(Password.Text, "sha1");
if (user.ToString() == HashedPassword)
{
Response.Redirect("faqs.aspx");
}
else
{
Response.Redirect("Default.aspx");
}
}
I put breakpoints and checked the data at each stage of the flow and the data in the object result set and in the string are the same but even then the conditional if fails
whats interesting is both the types being compared are of the type string and of the same value,so why is that that the redirect goes to the default.aspx page.
The image contains the data from the breakpoints
Any inputs would be great.
Thanks
Based on the screenshot, user.ToString() looks to be returning the string {System.Data.Objects.ObjectResult<string>}. This, of course, does not equal the hashed password.
Your problem is that the result of your getloginname call is a sequence of strings containing a single string, not a single string itself. The default implementation of ToString() simply returns the class name, and you can see it in the Value column for the "user" row in the screenshot. Changing your conditional statement to the following should fix it:
if (user.FirstOrDefault() == HashedPassword)
I'm trying to use LINQ to SQL to select a few specific columns from a table and return the result as a strongly typed list of objects.
For Example:
var result = (from a in DataContext.Persons
where a.Age > 18
select new Person
{
Name = a.Name,
Age = a.Age
}
).ToList();
Any help would be greatly appreciated.
It builds fine, but when I run it, I get the error. Explicit construction of entity type MyEntity in query is not allowed.
Basically you are doing it the right way. However, you should use an instance of the DataContext for querying (it's not obvious that DataContext is an instance or the type name from your query):
var result = (from a in new DataContext().Persons
where a.Age > 18
select new Person { Name = a.Name, Age = a.Age }).ToList();
Apparently, the Person class is your LINQ to SQL generated entity class. You should create your own class if you only want some of the columns:
class PersonInformation {
public string Name {get;set;}
public int Age {get;set;}
}
var result = (from a in new DataContext().Persons
where a.Age > 18
select new PersonInformation { Name = a.Name, Age = a.Age }).ToList();
You can freely swap var with List<PersonInformation> here without affecting anything (as this is what the compiler does).
Otherwise, if you are working locally with the query, I suggest considering an anonymous type:
var result = (from a in new DataContext().Persons
where a.Age > 18
select new { a.Name, a.Age }).ToList();
Note that in all of these cases, the result is statically typed (it's type is known at compile time). The latter type is a List of a compiler generated anonymous class similar to the PersonInformation class I wrote above. As of C# 3.0, there's no dynamic typing in the language.
UPDATE:
If you really want to return a List<Person> (which might or might not be the best thing to do), you can do this:
var result = from a in new DataContext().Persons
where a.Age > 18
select new { a.Name, a.Age };
List<Person> list = result.AsEnumerable()
.Select(o => new Person {
Name = o.Name,
Age = o.Age
}).ToList();
You can merge the above statements too, but I separated them for clarity.
The issue was in fact that one of the properties was a relation to another table. I changed my LINQ query so that it could get the same data from a different method without needing to load the entire table.
Thank you all for your help!
Make a call to the DB searching with myid (Id of the row) and get back specific columns:
var columns = db.Notifications
.Where(x => x.Id == myid)
.Select(n => new { n.NotificationTitle,
n.NotificationDescription,
n.NotificationOrder });
Currently in my ASP.Net applications web.config I have an application setting that stores a comma delimited list of mapping values, like the one below. In the code behind I need to perform a lookup on this data based on input values 1, 2, 3 etc. I can either string split it and loop until I find a match, or use Regex to pull the value from the config string.
Currently i'm using Regex to get the mapping value. I'm not opposed to changing how the data is stored in the web.config. Is there a more simple and elegant way of handling this?
<add key="Mappings" value="1|APP,2|TRG,3|KPK,4|KWT,5|CUT" />
If you need to use this lookup frequently and the string in web.config doesn't change very often, then it makes sense to parse the string once into a Dictionary object and store that in the Application or Cache.
Lookups from the Dictionary will be lightning fast, especially compared to parsing the string each time.
private static readonly object _MappingsLock = new object();
public static string GetMapping(int id)
{
// lock to avoid race conditions
lock (_MappingsLock)
{
// try to get the dictionary from the application object
Dictionary<int, string> mappingsDictionary =
(Dictionary<int, string>)Application["MappingsDictionary"];
if (mappingsDictionary == null)
{
// the dictionary wasn't found in the application object
// so we'll create it from the string in web.config
mappingsDictionary = new Dictionary<int, string>();
foreach (string s in mappingsStringFromWebConfig.Split(','))
{
string[] a = s.Split('|');
mappingsDictionary.Add(int.Parse(a[0]), a[1]);
}
// store the dictionary in the application object
// next time around we won't need to recreate it
Application["MappingsDictionary"] = mappingsDictionary;
}
// now do the lookup in the dictionary
return mappingsDictionary[id];
}
}
// eg, get the mapping for id 4
string mapping = GetMapping(4); // returns "KWT"
Just curious :) What about LINQ
string inputValue = "2";
string fromConfig = "1|APP,2|TRG,3|KPK,4|KWT,5|CUT";
string result = fromConfig
.Split(',')
.Where(s => s.StartsWith(inputValue))
.Select(s => s.Split('|')[1])
.FirstOrDefault();
Or
Regex parseRegex = new Regex(#"((?<Key>\d)\|(?<Value>\S{3}),?)");
parseRegex.Matches(fromConfig)
.Cast<Match>()
.Where(m => m.Groups["Key"].Value == inputValue)
.Select(m => m.Groups["Value"].Value)
.FirstOrDefault();
Split the string on commas, then each substring on |, store these in a Dictionary and find it by key.
That's just as an alternative to Regex. You know what they say about Regex.