Use Like in Linq query EF Core [duplicate] - c#

This question already has answers here:
Like Operator in Entity Framework?
(9 answers)
Closed 3 years ago.
I have the below method in the EF Core application
public List<Prj_Detail> GetByOrg(string org)
{
var data = _context.Prj_Details.Where(w => w.Account_Name == org).ToList();
return data;
}
Here instead of == I need to check for Like how can I do that in my method

Like others have said you can do a Contains operator however in some cases this casues an unncessary TSQL casting. Instead you could use the in-built Entity Framework functions like so:
_context.Prj_Details.Where(EF.Functions.Like(w.Account_Name, org)).ToList();

Have you tried using Contains?
var data = _context.Prj_Details.Where(w => w.Account_Name.Contains(org)).ToList();
You can use StartsWith and EndsWith too.
Here's more information about it.

Could try with Contains to filter.
Please refer the below code.
depending on LeftRim/RightTrim/upperCase/LowerCase
public List<Prj_Detail> GetByOrg(string org)
{
var data = _context.Prj_Details.Where(w => w.Account_Name.Contains(org)).ToList();
return data;
}

Related

Return a varchar from database using dapper [duplicate]

This question already has answers here:
Why Async function returning System.Threading.Tasks.Task`1[System.String]?
(2 answers)
Closed 4 years ago.
I need to retrieve a single word/varchar from the database ( it can be an empty string or a null value sometimes ).
I'm using dapper and I can't retrieve anything at all. The many tutorials and questions on the Web refer only to retrieve an Integer value, but never a String.
This is what I got so far:
using (var db = new FbConnection(csb.ToString()))
{
await db.OpenAsync();
result = db.ExecuteScalarAsync<string>("SELECT NOME from NACION WHERE NOME = #nacion", new { nacion }).ToString();
db.Close();
}
That result variable should be a string, like "Word" or an empty/null string, depending on the result of the query.
Right now, it's returning something weird like this: System.Threading.Tasks.Task'1[System.String]
What am I doing wrong?
You should await the call to the method ExecuteScalarAsync:
result = await db.ExecuteScalarAsync<string>(...);
Please note that you should not to call ToString().

'Int32 Userid()' method - The work before with LINQ but has gone to the entity framework [duplicate]

This question already has answers here:
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method
(3 answers)
Closed 6 years ago.
It's like I've gone from Linq to entity framework yesterday. but after I got right up in the code the different places on the page. but when I just need to log into the page so gives me problems.
LINQ to Entities does not recognize the method 'Int32 Userid()' method, and this method cannot be translated into a store expression.
The make mistakes when I need to find out whether the user has a session to know whether you are log in or not.
However, it is the first time I work with the EF(entity framework) but has long worked with Linq in about 2 years soon.
private static int Userid()
{
return Helper.BrugerInformation.SessionVale.SessionBrugerid();
}
public static string UserLayOut()
{
var checkuser = db.Users.FirstOrDefault(i => i.Id == Userid());
if(checkuser != null)
{
return "~/Views/Shared/_backendLayout.cshtml";
}
else
{
return "~/Views/Shared/_Layout.cshtml";
}
}
Return session info:
public const string BrugerId = "Brugerid";
public class SessionVale
{
public static int SessionBrugerid()
{
string brugerid = BrugerId;
return Convert.ToInt32(HttpContext.Current.Session[brugerid]);
}
}
How can I get done so that I can use the different values as I could before?
Use a local variable, eg
int userid = Userid();
var checkuser = db.Users.FirstOrDefault(i => i.Id == userid );

Iterate with LINQ over a list and set founded varible [duplicate]

This question already has answers here:
LINQ equivalent of foreach for IEnumerable<T>
(22 answers)
Closed 7 years ago.
I have this code and want to do the same with a linq statement.
foreach (var field in fieldExtension)
{
if (field.Name.Equals(item.Name))
{
field.Access = true;
}
}
It is easy to iterate over the list with:
fieldExtension.Where(field => field.Name.Equals(item.Name));
But is it posible to assign a value to the variable we have found in the list? I thought about something like this:
fieldExtension.Where(field => field.Name.Equals(item.Name)).Select(field => field.Access = true);
Does anybody know a way to do it correctly with linq? Because I don't want to split it up. Which would also work.
var result = fieldExtension.Where(field => field.Name.Equals(item.Name)).ToList();
result.FirstOrDefault().Access = true;
Why do you insist on linq? its not a good practice to use linq alll the time.
How ever you can mix linq with foreach.
foreach (var field in fieldExtension.Where(f => f.Name.Equals(item.Name)))
{
field.Access = true;
}

Is there any difference between sql linq [duplicate]

This question already has answers here:
Difference between Query Expression and Method Expression in LINQ?
(5 answers)
Closed 7 years ago.
I have a list of Pieces. I want an int[] of PieceID;
I try this, but this create an anonymous type[].
PiecesTop1 = new List<Piece>();
var test = PiecesTop1.Select(x => new {x.PieceID}).ToArray();
Then I found this syntaxis and works ok.
var lstPieceID = from p in PiecesTop1
select p.PieceID;
int[] arrPieceID = lstPieceID.ToArray();
int i = arrPieceID[0];
I usually use first sintaxis so not familiar with second one.
First question: How I make first sql to return an int[].
Second question: How can I call each of those sql query type to difference beetween them?
Is there any diference on what sintaxis should I use (just in case I'm not using any database).
var test = PiecesTop1.Select(x => x.PieceID).ToArray();

Dynamic table name in linq [duplicate]

This question already has answers here:
Querying data using Entity Framework from dynamically created table
(2 answers)
Dynamically set the table name in LINQ query
(3 answers)
Closed 8 years ago.
I'm trying to execute some LINQ commands using a dynamic table name. For example, instead of:
var o = (from x in context.users select x);
I want to use something like:
var o = (from x in getTableObjectByName("users", context) select x);
More or less. Here's the code I have so far, which both compiles and runs:
using (MySiteEntities ipe2 = new MySiteEntities()) {
var propinfo1 = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
var propval1 = propinfo1.GetValue(ipe2, null);
}
That runs, but always returns zero records. The users table most definitely contains records, and in any case when I call it directly using the first method above I get all of the records as expected. How can I modify my code to actually pull down records, rather than just an empty collection?
Edit: I've also tried this:
using (MySiteEntities ipe = new MySiteEntities())
{
var prop = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
Type dbsetType = typeof(DbSet<>);
dbsetType = dbsetType.MakeGenericType(Type.GetType("MySiteNamespace.user"));
Type t = dbsetType.GetType();
var val = prop.GetValue(ipe, null);
}
In this case, the code not only runs, but actually returns the results as expected. However, val is an Object. I need to cast it to the type DbSet<user>, which would be easy enough, except that the parameter user is only known at runtime....the cast needs to be dynamic as well. I've tried using Convert.ChangeType(val, t);, but that throws an
InvalidCastException (Object must implement IConvertible).
How can I convert the val variable to an actually usable object?
No idea if this is relevant, but this is on EntityFramework 4.
In your DbContext class, add a method say called Set that returns:
public DbSet Set(string name)
{
// you may need to fill in the namespace of your context
return base.Set(Type.GetType(name));
}
Which you can query like this:
using (var db = new YourDataContext())
{
// Since your DbSet isn't generic, you can can't use this:
// db.Set("Namespace.EntityName").AsQueryable().Where(a=> a.HasSomeValue...
// Your queries should also be string based.
// Use the System.Linq.Dynamic nuget package/namespace
var results = db.Set("Namespace.EntityName")
.AsQueryable()
.Where("SomeProperty > #1 and SomeThing < #2", aValue, anotherValue);
// you can now iterate over the results collection of objects
}
More information on System.Linq.Dynamic can be found here

Categories