LINQ orderby not working in Swedish culture - linq

How to set LINQ orderby based on CurrentUICulture
var actorQuery = (from actor in actorList
where !actor.IsLocked
select new { Id = actor.Id, Name = string.Format("{0} {1}", actor.Name, actor.BusinessId) }).OrderBy(actor => actor.Name);

The order is determined by CurrentCulture not CurrentUICulture
Example:
var a = new string[] {"å","ä","ö","a","b","c"};
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("sv-SE");
a.OrderBy(x => x).Dump(); //a,b,c,å,ä,ö
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
a.OrderBy(x => x).Dump(); //a,ä,å,b,c,ö
So just set CurrentCulture at the same time you set CurrentUICulture

Related

ef6 linq method returning $ref for nested entries in query

my linq method system from EF6 is returning $ref when I monitor results in fiddler. If I watch the local window in my webapi everything is populated correctly, but not in the actual results that are returned. It only affects the nested entries. anyone know what I am doing wrong? (I created models from database in EF6)
var student = dbEF.Accounts
.Where(x => x.AccountNumber == acctNum)
.Select(x => new DTOCrmDetails()
{
AccountNumber = x.AccountNumber,
CommissionId = x.CommissionId,
Commission = x.Commission,
ManagerID = x.ManagerID,
ManagerName = x.Manager.ManagerName,
Manager = x.Manager,
Employees = x.Manager.Employees,
WireInstructionsUSD = x.Manager.WireInstructionsUSDs
//Mapping_ManagersExecutingBrokers = x.Manager.Mapping_ManagersExecutingBrokers
}).FirstOrDefault();
return student;
these are my settings.
var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; config.Formatters.Remove(config.Formatters.XmlFormatter); config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
You need to disable your lazy loading in the entity framework dbcontext.
something like this way:
dbEF.Configuration.LazyLoadingEnabled = false;

Using Linq Returning all records matching all from a list of parameters

I have a simple table with CustomerID & ProductCode. Using the following Linq query I get a list of all IDs that bought 10EDUC or 12CONV and didn't buy 10CONV and 11CONV. What I need to do is get it to return the IDs for those that bought 10EDUC and 12CONV and didn't buy 10CONV and 11CONV.
Any thoughts? TIA
var IncludePredicate = PredicateBuilder.True<Products>();
var ExcludePredicate = PredicateBuilder.True<Products>();
List<string> IncludeProducts = new List<string>();
List<string> ExcludeProducts = new List<string>();
ExcludeProducts.Add("10CONV");
ExcludeProducts.Add("11CONV");
IncludeProducts.Add("10EDUC");
IncludeProducts.Add("12CONV");
IncludePredicate = IncludePredicate.And(m=>IncludeProducts.Contains(m.Service));
ExcludePredicate = ExcludePredicate.And(m => ExcludeProducts.Contains(m.Service));
var IncludeResults = (from d in Products
.AsExpandable()
.Where(IncludePredicate)
.Distinct()
select d.CustomerID
)
.Except(from ex in Services
.Where(ExcludePredicate)
select ex.CustomerID);

Filter SelectListItem value using some condition

I have one SelectListItem for DropDownList. I have to filter based on some condition. If I try adding the condition then its gives me an error like this (LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression). I ll be adding that code here. Please guide me to solve this.
Code
IEnumerable<SelectListItem> IssueId = (from txt in Db.Issues where txt.BibId == BibId
select new SelectListItem()
{
Text = txt.Description,
Value = txt.Id.ToString(),
Selected = true,
});
SelectList IssueIds = new SelectList(IssueId, "Value", "Text");
ViewBag.IssueId = IssueIds;
Thanks
Try this:
LINQ2EF does not know ToString() but after AsEnumerable() you'll get a local collection when ToString() is implemented.
IEnumerable<SelectListItem> IssueId =
(from txt in Db.Issues.Where(e => e.BibId == BibId).AsEnumerable()
select new SelectListItem()
{
Text = txt.Description,
Value = txt.Id.ToString(),
Selected = true
});
Linq To Sql can't generate TSQL for txt.Id.ToString()
You will need to iterate the result instead after executing the query, or cast to Enumerable as xeondev suggests.
That extension does not seem to be sorted by linq to Entities but you could just do the mapping once you have the issues, e.g.
var issues = (from issue in Db.Issues
where issue .BibId == BibId
select issue ).ToList();
IEnumerable<SelectListItem> IssueId = (from txt in issues
where txt.BibId == BibId
select new SelectListItem()
{
Text = txt.Description,
Value = txt.Id.ToString(),
Selected = true,
});

Linq select subquery

As the title states, I'm trying to perform a select subquery in Linq-To-SQL. Here's my situation:
I have a database view which returns the following fields:
SourceId
LicenseId
LicenseName
CharacteristicId
CharacteristicName
Now I want to be able to store this in a model of mine which has the following properties
Id
Name
Characteristics (this is List which has Id, Name and Icon => Icon is byte[])
Here's the query I wrote which doesn't work:
var licensesWithCharacteristics =
_vwAllLicensesWithAttributesAndSourceIdRepository.GetAll()
.Where(x => x.SourceID == sourceId)
.Select(a => new LicenseWithCharacteristicsModel()
{
LicenseId = a.LicenseId,
LicenseName = a.LicenseName
,CharacteristicList = _vwAllLicensesWithAttributesAndSourceIdRepository.GetAll()
.Where(x => x.LicenseId == a.LicenseId)
.Select(c => new CharacteristicModel { Id = c.CharacteristicID, Name = c.CharacteristicName, Icon = c.Icon })
.Distinct().ToList()
})
.Distinct().ToList();
How would you solve this? I'm trying to do this in one query to keep my performance up, but I'm kind of stuck.
Your sample query and models are not that coherent (where does Icon come from, Characteristics or CharacteristicList), but anyway.
I do this in two parts, you can of course regroup this in one query.
I enumerate the result after the grouping, you may try to do without enumerating (all in linq to sql, but not sure it will work).
var groupedResult =
_vwAllLicensesWithAttributesAndSourceIdRepository.GetAll()
.Where(x => x.SourceID == sourceId)
.GroupBy(m => new {m.LicenseId, m.LicenseName})
.ToList();
var results = groupedResult.Select(group => new LicenseWithCharacteristicsModel {
LicenseId = group.Key.LicenseId,
LicenseName = group.Key.LicenseName,
Characteristics = group.Select(m=> new CharacteristicModel {
Id = m.CharacteristicId,
Name = m.CharacteristicName
}).ToList()
});
in "single query"
_vwAllLicensesWithAttributesAndSourceIdRepository.GetAll()
.Where(x => x.SourceID == sourceId)
.GroupBy(m => new {m.LicenseId, m.LicenseName})
.Select(group =>
new LicenseWithCharacteristicsModel
{
LicenseId = group.Key.LicenseId,
LicenseName = group.Key.LicenseName,
Characteristics = group.Select(m =>
new CharacteristicModel
{
Id = m.CharacteristicId,
Name = m.CharacteristicName
}).ToList()
});

Weird behaviour with Linq

I have a Windows forms application (.NET 4.0) running with a Sql Server CE 3.5 database, which I access via an EF connection.
Here is my initial query, which returns two results:
var list = db.UserPresentation
.Select(up => new
{
UserPresentationID = up.UserPresentationID,
PresentationName = up.PresentationName,
DateRequested = up.DateRequested,
Edit = string.Empty,
Delete = string.Empty,
Download = string.Empty
})
.OrderByDescending(up => up.DateRequested)
.ToList();
Now I introduce an external variable and a where clause, and it returns zero results. If I run this same code in LinqPad, it returns 2 results.
int userID = 2;
// load list of user presentations
var list = db.UserPresentation
.Where(up => up.UserID == userID)
.Select(up => new
{
UserPresentationID = up.UserPresentationID,
PresentationName = up.PresentationName,
DateRequested = up.DateRequested,
Edit = string.Empty,
Delete = string.Empty,
Download = string.Empty
})
.OrderByDescending(up => up.DateRequested)
.ToList();
Now I hardcode the userid inside the query, and it returns two results again:
var list = db.UserPresentation
.Where(up => up.UserID == 2)
.Select(up => new
{
UserPresentationID = up.UserPresentationID,
PresentationName = up.PresentationName,
DateRequested = up.DateRequested,
Edit = string.Empty,
Delete = string.Empty,
Download = string.Empty
})
.OrderByDescending(up => up.DateRequested)
.ToList();
I'm really stumped. Any idea what's going on here?
Is UserID nullable?
If so be sure to do .Where(up => up.UserID.HasValue && up.UserID.Value == userID)
I had something similar with a nullable datetime once
Have you tried assigning the same hard coded value inside your variable? My guess is that the value in your variable is not found among your data, that is if you are sure that the variable name is correct.

Resources