Selecting only one column linq lambda query asp.net - asp.net

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

Related

i need to retrieve last data row single data

I need to retrieve the last row one data field. id is the primary key of my table. I'm trying to retrieve my final row data using its id
public AddExpenses[] GetFinalExpense(int numberOfExpenses)
{
return Conn.Table<AddExpenses>()
.OrderByDescending(expenses => expenses.Id)
.Take(numberOfExpenses)
.ToArray();
}
In my view model I have
var finalexpense = database.GetFinalExpense(1);
this is my code. when I tried to use this final row data to retrieve single data
ExpenseLabel = "Your expense is"+finalexpense;
in here final expense it does not show properties of the table to call. I need my finalexpense property to call it does not work
Concatenating a string with an object uses the default implementation of ToString which will yield something like AddExpenses[] for you, if finalexpense has a value !=null, since it is an array.
First of all, you'll have to get the item in the array
var finalExpenses = database.GetFinalExpense(1);
var finalExpense = finalExpenses[0];
Furthermore you'll have to make sure that your object is formatted properly. You could implement your own ToString method in AddExpenses class, but the simplest way would be to use string interpolation
var formattedExpense = $"{finalExpense.Expense} ({finalExpense.Date}, {finalExpense.Category})";
ExpenseLabel = $"Your expense is {formattedExpense}";
How you build formattedExpense is up to you, take the proposed string as a starting point and adapt it to your needs.

What should be the type parameter for List<T> and .Query<T> for joined table?

I am very new to Xamarin Forms and SQLite. I have the following method that returns a list from two joined tables. My problem is I don't know what is the right type parameter the List<T> and .Query<> should have to be able to get the values of both Category and Phrase table. Can anyone enlighten me on this one?
public List<?> GetWordsByCategory(int category)
{
lock (locker)
{
var words = databaseConnection
.Query<?>("Select Category.*, Phrase.*
From Category
Join Phrase on Category.Id = Phrase.CategoryId
Where Category.Id = 1")
.ToList();
return words;
}
}
I have tried List<Category> but would only return the properties of the Category table likewise List<Phrase>
You can return a dynamic or create a new class.
But I would suggest you to use the SQLite.Net PCL which is a wrapper around SQL and which enables you to query database like EF using linq and lamda than string queries.
You can look into this similar question which should help you.

Spring JDBC Dynamic Query into Map of objects

I have to dynamically execute queries which will come from database.The query has dynamic fields,which needs to be converted into map as key value pairs and send to view.For ex
one query may return only one fields and other may return more than two field of multiple rows.I have to write code in such way that it will work for n no.of fields and return it as map using spring jdbc.
Spring offers two ways to solve your problem.
Approach 1: use queryForList method from JdbcTemplate class. this will return List of Map populated by column names as key , and DB record as value. you have to manualy iterate over the list. each map object inside the list represents a single row in resultset.
example :
List<Map<String, Object>> result = jdbcTemplate.queryForList(query, new Object[]{123});
Iterator items = result.iterator();
while(items.hasNext()){
Map<String, Object> row = (Map<String, Object>) items.next();
System.out.println(row);
}
Approach 2 : this dosen't exactly match your requirements, but little faster than the first approach also more coding involved. you can use queryForRowSet method.
SqlRowSet rowSet = jdbcTemplate.queryForRowSet(query, new Object[]{3576});
int columnCount = rowSet.getMetaData().getColumnCount();
System.out.println(columnCount);
while(rowSet.next()){
for(int id =1 ; id <= columnCount ; id ++){
System.out.println(rowSet.getString(id)) ;
// your custom logic goes here
}
}

LINQ to SQL - How to select specific columns and return strongly typed list

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

ASP.Net Mapping Values Lookup

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.

Resources