How to ensure linq statement will not fail - c#

what's correct way to ensure this linq statment will be executed as expect, by that I mean all params will be populated (not null values).
Here is example:
public async Task<IEnumerable<articles>> GetArticlesByStatus(articleRequest request)
{
var query = await _context.article.AsNoTracking()
.Where(x => x.ArticleStatusId == (int)request.ArticleStatus).ToListAsync();
}
One thing might be issue and that is request.ArticleStatus, if that's null than this statment wont be correct..
I've tried with something like this:
public async Task<IEnumerable<articles>> GetArticlesByStatus(articleRequest request)
{
if(request.Status.HasValue) // Included .HasValue but I guess there's more elegant one line solution?
{
var query = await _context.article.AsNoTracking()
.Where(x => x.ArticleStatusId == (int)request.ArticleStatus).ToListAsync();
}
}
Thanks
Cheers

If the method accepts an ArticleStatus instead of an articleRequest, it won't fail, i.e. you will never get an InvalidCastException at runtime, unless ArticleStatus is nullable (ArticleStatus?) or has another underlying type than int (which is the default underlying type for enums):
public async Task<IEnumerable<articles>> GetArticlesByStatus(ArticleStatus status)
{
var query = await _context.article.AsNoTracking()
.Where(x => x.ArticleStatusId == (int)status).ToListAsync();
}
I've assumed that ArticleStatus is an enum.
If you keep the articleRequest parameter and articleRequest is a nullable reference type, you should check whether it's null before you try to access its Status property:
Where(x => request == null || x.ArticleStatusId == (int)request.Status)
Beware that ORMs like Entity Framework may not be able to translate your predicate(s) to valid SQL.

If request.ArticleStatus is a Nullable<ArticleStatus> then you could just cast it to a Nullable<int> in your query.
public async Task<IEnumerable<articles>> GetArticlesByStatus(articleRequest request)
{
var query = await _context.article.AsNoTracking()
.Where(x => x.ArticleStatusId == (int?)request.ArticleStatus).ToListAsync();
return query;
}
This assumes that request isn't null, which is something you'd need to check for.
That said, personally I prefer what you posted. I'm not sure what you mean by "more elegant", but if you know in advance from the state of request that the query won't have any results... why run it? Why not just skip sending a query to the database and just return Enumerable.Empty<articles>() instead?

Related

EF linq query where condition based on bool parameter

I have an EF linq query where I want to set a where condition based on a true/false parameter. I can do something similar in SQL which is somewhat how I've written my EF query but it doesnt seem to work with EF Core.
When I expect the executed SQL if I pass "activeOnly = true" then no SQL where condition is applied and when I pass "activeOnly = false" then the condition is "where 0 = 1".
Clearly I have this wrong but I cant figure out the right way to do this? Or if its possible?
public async Task<List<UserDto>> GetUsersAsync(string region, bool activeOnly)
{
var allUsers = new List<UserDto>();
var countries = _configuration.GetRegionConfiguration(region).Countries;
foreach (var country in countries)
{
_context.ChangeConnectionString(country.DatabaseConnectionString);
var users = await _context.User
.ProjectTo<UserDto>(_mapper.ConfigurationProvider)
.Where(x => (activeOnly && (x.RoleIds != null)) || (!activeOnly && (x.RoleIds == null)))
.ToListAsync();
allUsers.AddRange(users);
}
allUsers.OrderBy(x => x.FullName);
return allUsers;
}
Current versions emit a helpful warning when you use this kind of query:
Collection navigations are only considered null if their parent entity is null. Use 'Any' to check whether collection navigation 'YourEntity.YourNavigationColleciton' is empty.
So instead of
x.RoleIds != null
use
x.RoleIds.Any()

Getting a single object from mongodb in C#

I've picked up a piece of code that is using the MongoDB driver like this to get a single object from a collection...this can't be right, can it? Is there a better way of getting this?
IMongoCollection<ApplicationUser> userCollection;
....
userCollection.FindAsync(x => x.Id == inputId).Result.ToListAsync().Result.Single();
Yes, there is.
First of all don't use FindAsync, use Find instead. On the IFindFluent result use the SingleAsync extension method and await the returned task inside an async method:
async Task MainAsync()
{
IMongoCollection<ApplicationUser> userCollection = ...;
var applicationUser = await userCollection.Find(_ => _.Id == inputId).SingleAsync();
}
The new driver uses async-await exclusively. Don't block on it by using Task.Result.
You should limit your query before executing, otherwise you will first find all results and then only read one of it.
You could either specify the limit using FindOptions in FindAsync, or use the fluent syntax to limit the query before executing it:
var results = await userCollection.Find(x => x.Id == inputId).Limit(1).ToListAsync();
ApplicationUser singleResult = results.FirstOrDefault();
The result from ToListAsync will be a list but since you limited the number of results to 1, that list will only have a single result which you can access using Linq.
In newer versions of MongoDB Find() is deprecated, so you can either use
collection.FindSync(o => o.Id == myId).Single()
or
collection.FindAsync(o => o.Id == myId).Result.Single()
You can also use SingleOrDefault(), which returns null if no match was found instead of throwing an exception.
I could not get the method:
coll.Find(_ => _.Id == inputId).SingleAsync();
To work as I was getting the error
InvalidOperationException: Sequence contains more than one element c#
So I ended up using .FirstOrDefault()
Example:
public FooClass GetFirstFooDocument(string templatename)
{
var coll = db.GetCollection<FooClass>("foo");
FooClass foo = coll.Find(_ => _.TemplateName == templatename).FirstOrDefault();
return foo;
}

Dynamically select columns in runtime using entity framework

I have an existing function like this
public int sFunc(string sCol , int iId)
{
string sSqlQuery = " select " + sCol + " from TableName where ID = " + iId ;
// Executes query and returns value in column sCol
}
The table has four columns to store integer values and I am reading them separately using above function.
Now I am converting it to Entity Framework .
public int sFunc(string sCol , int iId)
{
return Convert.ToInt32(TableRepository.Entities.Where(x => x.ID == iId).Select(x => sCol ).FirstOrDefault());
}
but the above function returns an error
input string not in correct format
because it returns the column name itself.
I don't know how to solve this as I am very new to EF.
Any help would be appreciated
Thank you
Not going to be useful for the OP 8 years later, but this question has plenty of views, so I thought it could be helpful for others to have a proper answer.
If you use Entity Framework, you should do Linq projection (Select()), because that leads to the correct, efficient query on the db side, instead of pulling in the entire entity.
With Linq Select() you normally have to provide a lambda, though, so having your your column/property name in a string poses the main difficulty here.
The easiest solution is to use Dynamic LINQ (EntityFramework.DynamicLinq Nuget package). This package provides alternatives to the original Linq methods, which take strings as parameters, and it translates those strings into the appropriate expressions.
Example:
async Task<int> GetIntColumn(int entityId, string intColumnName)
{
return await TableRepository.Entities
.Where(x => x.Id == entityId)
.Select(intColumnName) // Dynamic Linq projection
.Cast<int>()
.SingleAsync();
}
I also made this into an async call, because these days all database calls should be executed asynchronously. When you call this method, you have to await it to get the result (i.e.: var res = await GetIntColumn(...);).
Generic variation
Probably it's more useful to change it into an extension method on IQueryable, and make the column/property type into a generic type parameter, so you could use it with any column/property:
(Provided you have a common interface for all your entities that specifies an Id property.)
public static async Task<TColumn> GetColumn<TEntity, TColumn>(this IQueryable<TEntity> queryable, int entityId, string columnName)
where TEntity : IEntity
{
return await queryable
.Where(x => x.Id == entityId)
.Select(columnName) // Dynamic Linq projection
.Cast<TColumn>()
.SingleAsync();
}
This is called like this: var result = await TableRepository.Entities.GetColumn<Entity, int>(id, columnName);
Generic variation that accepts a list of columns
You can extend it further to support selecting multiple columns dynamically:
public static async Task<dynamic> GetColumns<TEntity>(this IQueryable<TEntity> queryable, int entityId, params string[] columnNames)
where TEntity : IEntity
{
return await queryable
.Where(x => x.Id == entityId)
.Select($"new({string.Join(", ", columnNames)})")
.Cast<dynamic>()
.SingleAsync();
}
This is called like this: var result = await TableRepository.Entities.GetColumns(id, columnName1, columnName2, ...);.
Since the return type and its members are not known compile-time, we have to return dynamic here. Which makes it difficult to work with the result, but if all you want is to serialize it and send it back to the client, it's fine for that purpose.
This might help to solve your problem:
public int sFunc(string sCol, int iId)
{
var _tableRepository = TableRepository.Entities.Where(x => x.ID == iId).Select(e => e).FirstOrDefault();
if (_tableRepository == null) return 0;
var _value = _tableRepository.GetType().GetProperties().Where(a => a.Name == sCol).Select(p => p.GetValue(_tableRepository, null)).FirstOrDefault();
return _value != null ? Convert.ToInt32(_value.ToString()) : 0;
}
This method now work for dynamically input method parameter sCol.
Update:
This is not in context of current question but in general how we can select dynamic column using expression:
var parameter = Expression.Parameter(typeof(EntityTable));
var property = Expression.Property(parameter, "ColumnName");
//Replace string with type of ColumnName and entity table name.
var selector = Expression.Lambda<Func<EntityTable, string>>(property, parameter);
//Before using queryable you can include where clause with it. ToList can be avoided if need to build further query.
var result = queryable.Select(selector).ToList();
You have to try with dynamic LINQ. Details are HERE
Instead of passing the string column name as a parameter, try passing in a lambda expression, like:
sFunc(x => x.FirstColumnName, rowId);
sFunc(x => x.SecondColumnName, rowId);
...
This will in the end give you intellisense for column names, so you avoid possible errors when column name is mistyped.
More about this here: C# Pass Lambda Expression as Method Parameter
However, if you must keep the same method signature, i.e. to support other/legacy code, then you can try this:
public string sFunc(string sCol , int iId)
{
return TableRepository.Entities.Where(x => x.ID == iId).Select(x => (string) x.GetType().GetProperty(sCol).GetValue(x)});
}
You might need to adjust this a bit, I didn't have a quick way of testing this.
You can do this:
var entity = _dbContext.Find(YourEntity, entityKey);
// Finds column to select or update
PropertyInfo propertyInfo = entity.GetType().GetProperty("TheColumnVariable");

Comparing a nullable column throws "Unable to cast the type..." exception

My entity NewsItem has a nullable foreign key property: LibraryID of type int?.
My issue is when I query the property and compare it with any value except null, I get exceptions.
Initially my code was:
int? lid = ...
var results = context.NewsItems
.Where(n => n.LibraryID == lid);
but it gives me no results at all, no matter what lid is.
So, I tried:
var results = context.NewsItems
.Where(n => n.LibraryID.Equals(lid));
gives exception:
Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.
and then I tried:
var results = context.NewsItems
.Where(n => lid.Equals(n.LibraryID));
and got:
Unable to cast the type 'System.Nullable`1' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.
and this:
var results = context.NewsItems
.Where(n => object.Equals(lid, n.LibraryID));
gives same exception as the last one.
Now I was desperate, so I tried to complicate stuff (like other forums suggested, for example here):
var results = context.NewsItems
.Where(n => (lid == null ? n.LibraryID == null : n.LibraryID == lid));
but still getting same exception.
So... any SIMPLE workarounds?
How about
var results = context.NewsItems
.Where(n => lid.HasValue ? lid.Value == n.LibraryId.Value : (!n.LibraryId.HasValue) );
Hmm, that first snippet should work. I've used nullables like that many times. First thing I'd do is a sanity check just to make sure LibraryID is really int? and not long? or similar.
Other than that, you can try this:
var results = context.NewsItems
.Where(n => (lid.HasValue ? n.LibraryID == lid.Value : !n.LibraryID.HasValue));
Or to avoid the ?: within the query:
var results = lid.HasValue
? context.NewsItems.Where(n => n.LibraryID == lid.Value)
: context.NewsItems.Where(n => !n.LibraryID.HasValue);
It seems that EF does not find the correct operator overload. Therefore it produces wrong results if you set lid = null.
Use linq to objects by adding AsEnumerable() to your query and everything is fine:
var results = context.NewsItems.AsEnumeryble().Where(n => n.LibraryID == lid);
According to the MSDN docs (which I finally found), .Where() will only filter your collection. If you want to see if there are actually results, resolve by lazily executing the filtered query with .ToList(), GetEnumerator, or enumerating the collection with foreach;
This method is implemented by using deferred execution. The immediate
return value is an object that stores all the information that is
required to perform the action. The query represented by this method
is not executed until the object is enumerated either by calling its
GetEnumerator method directly or by using foreach in Visual C# or For
Each in Visual Basic.
http://msdn.microsoft.com/en-us/library/bb534803.aspx
int? lid = ...
var results = context.NewsItems
.Where(n => n.LibraryID == lid).ToList();
var results = context.NewsItems
.Where(n => n.LibraryID.HasValue && n.LibraryID.Value == lid.Value );
edit:
Previous filter was based on my understanding that you wanted to filter to entires having a particular value. Updated will filter to null or value.
var results = context.NewsItems
.Where(n => !n.LibraryID.HasValue || n.LibraryID.Value == lid.Value );

How to use LINQ Contains() to find a list of enums?

I have an enum called OrderStatus, and it contains various statuses that an Order can be in:
Created
Pending
Waiting
Valid
Active
Processed
Completed
What I want to do is create a LINQ statement that will tell me if the OrderStaus is Valid, Active, Processed or Completed.
Right now I have something like:
var status in Order.Status.WHERE(status =>
status.OrderStatus == OrderStatus.Valid ||
status.OrderStatus == OrderStatus.Active||
status.OrderStatus == OrderStatus.Processed||
status.OrderStatus == OrderStatus.Completed)
That works, but it's very "wordy". Is there a way to convert this to a Contains() statement and shorten it up a bit?
Sure:
var status in Order.Status.Where(status => new [] {
OrderStatus.Valid,
OrderStatus.Active,
OrderStatus.Processed,
OrderStatus.Completed
}.Contains(status.OrderStatus));
You could also define an extension method In() that would accept an object and a params array, and basically wraps the Contains function:
public static bool In<T>(this T theObject, params T[] collection)
{
return collection.Contains(theObject);
}
This allows you to specify the condition in a more SQL-ish way:
var status in Order.Status.Where(status =>
status.OrderCode.In(
OrderStatus.Valid,
OrderStatus.Active,
OrderStatus.Processed,
OrderStatus.Completed));
Understand that not all Linq providers like custom extension methods in their lambdas. NHibernate, for instance, won't correctly translate the In() function without additional coding to extend the expression parser, but Contains() works just fine. For Linq 2 Objects, no problems.
I have used this extension:
public static bool IsIn<T>(this T value, params T[] list)
{
return list.Contains(value);
}
You may use this as the condition:
Where(x => x.IsIn(OrderStatus.Valid, ... )
If that set of statuses has some meaning, for example those are statuses for accepted orders, you can define an extension method on your enum and use that in your linq query.
public static class OrderStatusExtensions
{
public static bool IsAccepted(this OrderStatuses status)
{
return status == OrderStatuses.Valid
|| status == OrderStatuses.Active
|| status == OrderStatuses.Processed
|| status == OrderStatuses.Completed;
}
}
var acceptedOrders = from o in orders
where o.Status.IsAccepted()
select o;
Even if you could not give the method a simple name, you could still use something like IsValidThroughCompleted. In either case, it seems to convey a little more meaning this way.
Assumnig that the enum is defined in the order you specified in the question, you could shorten this by using an integer comparison.
var result =
Order.Status.Where(x =>
(int)x >= (int)OrderStatus.Valid &
& (int)x <= (int)OrderStatus.Completed);
This type of comparison though can be considered flaky. A simply re-ordering of enumeration values would silently break this comparison. I would prefer to stick with the more wordy version and probably clean up it up by refactoring out the comparison to a separate method.
You could put these in a collection, and use:
OrderStatus searchStatus = new[] {
OrderStatus.Valid,
OrderStatus.Active,
OrderStatus.Processed,
OrderStatus.Completed };
var results = Order.Status.Where(status => searchStatus.Contains(status));

Categories

Resources