Querying against multiple columns in Entity Framework 6 - c#

I'm trying to execute a query against multiple columns in EF 6 (using C# WPF on VS 2013), I need to select all fields of some columns. I really don't know much but I already tried to do it with Linq and it doesn't seem to have that functionality, so I went with <context>.Database.SqlQuery<string>(query), but it's unclear to me how should I handle what it returns. The query is something simple like "SELECT column1,column2 FROM table".
Is it possible to do it with Linq? How? And for the SqlQuery() case, How should I handle it's result, being most of its columns are in string format?

#MiloGP yes you can do it with using Lambda Expression with LINQ
Here a example:
I have 5 columns in table employee(emp_id,emp_name,emp_dob,emp_address,emp_reference)
and My DBContext name : EmployeeEntities;
I trying to get emp_name and emp_address
List<employee> = EmployeeEntities.employees.select( x => new { x.emp_name, x.emp_address }).ToList();
if you need to get value of someone, As a example emp_id == 13458
List<employee> = EmployeeEntities.employees.Select( x => new { x.emp_name, x.emp_address }).Where( y => y.emp_id == 13458).ToList();

Related

NHibernate queryover how to query a field which starts with any value in a list

How to write a proper nhibernate queryover query to select records from a table which has got a column value which starts with any of the value in my inmemory list?
I am trying something like below
select * from table where title like 'AA%' or 'BB%' or 'CC%'
Thanks
I have not tested this, but I think it goes like this.
var disjunction = new Disjunction();
disjunction.Add(Restrictions.On<YourType>(x => x.Title).IsLike('AA%');
disjunction.Add(Restrictions.On<YourType>(x => x.Title).IsLike('BB%');
disjunction.Add(Restrictions.On<YourType>(x => x.Title).IsLike('CC%');
_session.QueryOver<YourType>().Where(disjunction);

Using a class in joining to database table with EF

If I have a summary class of some objects I need ( for example its primary key, etc..) is there a way to use a list of that class object when I am writing a joining to other tables? so all the things in my LINQ query are real table like this.Context.MyTable but one of them be my List<MyClass> ?
or is there any LINQ related Nuget project that makes this possible?
The EF LINQ queries aren't actually code that is run in C#, they are converted to SQL and run on the database server; so you can't join them with an in-memory array (or List<T>). What you can do, is use Contains like so:
public IEnumerable<Table1> GetThingsFromDatabse(DataContext db, IList<MyObject> objects)
{
var ids = objects.Select(x => x.Id).ToList();
var results = Enumerable.ToList(
from x in db.Table1s
where ids.Contains(x.Id)
select x
);
return results;
}
This gets translated into SQL that looks like this:
SELECT *
FROM [Table1] x
WHERE x.Id IN (#Id1, #Id2, ...)

Linq List Contains Method

Im newbie to linq and im using linq query to retrieve data from the table.My idea is to list all the cashsafes corresponding to a particular user and show it in dropdownlist.
The table structure is shown below
Table 1
cashsafeid cashsafename
1 cashsafe1
2 cashsafe2
3 cashsafe3
Table 2
Id UserId Cashsafeid
1 100 1,2,3
2 101 1,3
I've to get the cashsafename of a particular user say 100.How can i achieve it
The below code is the one i've tried but am stuck
List<Cashsafe> cashsafes=(from c in db.Table 1
where c.CashsafeId contains() )--Cannot go further
You store User's Cachsafeid column in very inefficient way - it doesn't allow to generate efficient SQL for LINQ provider. So the following solution has bad performance - if you care about that - change your table structure.
var user = db.Table2.Single(u => u.UserId == 100);
var cachfeIds = user.Cashsafeid.Split(',').Select(int.Parse).ToArray();
var cachefes = db.Table1.Where(c => cachfeIds.Contains(c.Id)).ToList();
Basically you need to join to tables, but foreign key is "virtual" - it is only in your mind. To retrieve foreign key values we must split the Cachsafeid column's value of every user to retrieve linked cachefes. And only then retrieve the cachefes with separate request (I think LINQ will retrieve all values from table and the execute Where part in C# code).
if you have no idea of join you can use
int x = 0;
List<int> Users = db.table2.FirstOrDefault(m => m.UserId == 100).Cashsafeid.Split(',').ToList().Where(str => int.TryParse(str, out x)).Select(str => x).ToList(); ;
var content = db.table1.Where(m => Users.Contains(m.cashsafeid)).ToList();

Linq to Sql Query returning same record twice

I am querying the database using Linq to Sql. Here is my data :
Name LastName Age
------------------------------
1 Abc Def 15
2 Abc Def 17
3 xyz wss 17
My Linq to Sql Code is :
Context _context = new Context("Conn_String");
var table = _context.GetTable<Person>();
List<Person> persons = table.Where<Person>(p => p.Name == "Abc" && p.LastName == "Def").ToList<Person>();
According to my understanding, This query should return 2 records. i.e. Record 1 and Record 2. But it is returning Record 1 twice. Can you enlighten me if it is a bug in Linq to Sql or something I am doing wrong?
EDIT:
This is my DAL Code:
public List<T> GetList<T>(Expression<Func<T, bool>> predicate) where T : class
{
try
{
Context _context = new Context("Conn_String");
var table = _context.GetTable<T>();
return table.Where<T>(predicate).ToList<T>();
}
catch (Exception ex)
{
throw ex;
}
}
I am calling this method as :
List<Person> person = DAL.GetList<Person>(p => p.Name == "Abc" && p.LastName == "Def");
foreach(var Person in persons )
{
// Print(person.Age);
}
I've just run into this issue myself.
Check which property the model has inferred to be your entity key for your Person class.
If it has a non-unique column as the entity key it will will use the first row which matches the value for each row when converting using ToList()
Short answer, You need to add the Primary key in the data your fetching.
You can simply add a column to your view select statement which is unique. You don’t have to use that column in your program but it will allow EF to properly build each object for you.
Although the question was asked in Nov 2012 and I am answering in Jul 2019. But the detailed answer is available at the below source.
I am answering maybe thing might help someone out there.
LINQ in .NET returning duplicate rows from a working SQL view
https://www.itworld.com/article/2833108/linq-in--net-returning-duplicate-rows-from-a-working-sql-view--solved-.html
Hi Usman,
This is my table :
Here i am using the following query :
using (DataClassesDataContext dc = new DataClassesDataContext())
{
var v = (from c in dc.t_controls where (c.config_display == "SHOW_VA" && c.next_value == 1) select c.description).ToList();
}
This query returns all the 5 rows.Take it as reference and check where are you wrong.Hope it help you.
Can you run your query and profile it using SQL Server profiler (assuming SQL Server) in the database. I am wondering if you have duplicate records in your table..or if there is a join causing duplicates.
I have used LINQ to SQL with no problems.
If the database profile comes out correct and you want to "force it" to be unique you can always pass a distinct method in your LINQ query at the end.

Querying two different entity types using PredicateBuilder

I am desperately trying to use LinqKits PredicateBuilder to allow the user to enter a search term into a text box and return records from two database tables/entitysets but I'm struggling to get anywhere. The (simplified) database structure is as follows:
Person Alias
------ ------
A_ID
P_ID ---------------< P_ID
P_FIRST_NAME A_FIRST_NAME
P_SURNAME A_SURNAME
So, each person can have 0 or many aliases. What I am trying to do is allow the user to search on a name and pull back the rows from the Person table where that name matches that in either the Person or the Alias table. So far I have got:
var peopleQuery = MainFrm.genesisContext.People.AsExpandable();
var peoplePredicate = PredicateBuilder.True<Person>();
var aliasQuery = MainFrm.genesisContext.Alias.AsExpandable();
var aliasPredicate = PredicateBuilder.False<Alias>();
if (!String.IsNullOrEmpty(txtFirstName.Text.Trim()))
{
peoplePredicate = peoplePredicate.And(p => p.P_FIRST_NAME == txtFirstName.Text);
aliasPredicate = aliasPredicate.And(a => a.A_FIRST_NAME == txtFirstName.Text);
peoplePredicate = peoplePredicate .Or(p => aliasPredicate);
}
This doesn't work because I'm trying to convert from People to Alias. Basically I'm completely stuck and not sure whether it is even possible to do an Or query on two different tables(?)
I can think of several possible solutions:
Include the primary name of each person in the
Alias table, and just search on the
Alias table, or
UNION the two tables together before
the search, or
Run a Linq query that outer joins the Alias table to the Person table,
and use the result in your search,
including your OR condition

Categories