I am using Entity Framework 6 Code First, all of my navigation properties looks correct. What I want to do in linq is to update multiple values in the one (entity) table with calculated values from the other (entity) table. The required outcome is the sql below,
UPDATE SalesDealItemChange
SET Price = SD.Rate * #FactorRate
FROM SalesDealItemChange SC
INNER JOIN [SalesDealItems] SD
ON SC.SalesDealItemID = sd.ID
WHERE SD.SalesDealID = #SalesDeal
I have tried the following linq, but i am not sure how to isolate the update to the SalesDealItemChange
context.SalesDealItems
.Include(x => x.SalesDealItemChanges)
.Where(x => x.SalesDealID == #SalesDeal)
.ForEach(x =>
{
x.SalesDealItemChanges.Price = x.ListPrice * #FactorRate;
});
context.SaveChanges();
Regards,
Related
I have an Asp.net core web API that uses EF Core DB first approach. I have the following Tables in my SQL server database.
Application table - contains a list of Applications.
Role table - contains a list of Roles (user, admin, Super Admin, etc.)
User table - contains a list of Users
User Role table - contains a mapping between User and Role table
Feature tables - contains a list of Features (Home page, user management, etc.)
RoleFeature table - contains the mapping between Feature and Role table
I am trying to get the RoleName and list of features for the given UserId and appId.
Below is the Linq query I have so far:
RoleDto role =
from a in ctx.Application.Where(x => x.ApplicationId == appId)
from r in ctx.Role.Where(x => x.ApplicationId == a.ApplicationId)
from ur in ctx.UserRole.Where(x => x.UserId == userId && x.RoleId == r.RoleId)
from rf in ctx.RoleFeature.Where(x => x.RoleId == ur.RoleId)
from f in ctx.Feature.Where(x => x.FeatureId == rf.FeatureId).Where(x => x.IsActive)
group new { r.RoleName, f.FeatureId } by ur.RoleId into g
select new RoleDto
{
Name = g.Select(x => x.RoleName).FirstOrDefault(),
FeatureIds = g.Select(x => x.FeatureId).ToList()
}.AsNoTracking()
However, I am getting an error saying unable to translate the LINQ expression.
The problem is with the FirstOrDefault() in the select section of the "groupby" query.
You are probably using ef core version higher than 2.1 and there are some changes in handling groupby query. You should take a look at the following link :
https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-2.1#linq-groupby-translation
Before version 2.1, in EF Core the GroupBy LINQ operator would always
be evaluated in memory. We now support translating it to the SQL GROUP
BY clause in most common cases.
So the query should be translated to SQL GROUP BY, but methods such as FirstOrDefault() can not be translated. As a fast solution you can change FirstOrDefault() with Max(), Min() or other aggregate functions that are supported in DB.
You don't need to select the Application. You can start by selecting Role directly as -
from r in dbCtx.Role.Where(x => x.ApplicationId == appId)
This will simplify the final SQL generated by EF. So the query will be faster.
If a User has multiple Role then you are trying to take the first one. You should do that when you are selecting Role as -
from r in ctx.Role.Where(x => x.ApplicationId == a.ApplicationId).Take(1)
Finally, you can fetch a list of RoleName and FeatureId, and then do the grouping on client side -
var query =
from r in dbCtx.Role.Where(x => x.ApplicationId == appId).Take(1)
from ur in dbCtx.UserRole.Where(x => x.UserId == userId && x.RoleId == r.RoleId)
from rf in dbCtx.RoleFeature.Where(x => x.RoleId == ur.RoleId && x.Feature.IsActive)
select new
{
RoleName = rf.Role.RoleName,
FeatureId = rf.FeatureId
};
var roleDto = query.AsNoTracking()
.AsEnumerable()
.GroupBy(p => p.RoleName)
.Select(g => new RoleDto
{
Name = g.Key,
FeatureIds = g.Select(p => p.FeatureId).ToList()
})
.FirstOrDefault();
I want to change code below to be sql translateable because now i get exception.
Basicallly i want list of customers from certain localisation and there could be more than one customer with the same CustomerNumber so i want to take the one that was most recently added.
In other words - distinct list of customers from localisation where "distinct algorithm" works by taking the most recently added customer if there is conflict.
The code below works only if it is client side. I could move Group By and Select after ToListAsync but i want to avoid taking unnecessary data from database (there is include which includes list that is pretty big for every customer).
var someData = await DbContext.Set<Customer>()
.Where(o => o.Metadata.Localisation == localisation)
.Include(nameof(Customer.SomeLongList))
.GroupBy(x => x.CustomerNumber)
.Select(gr => gr.OrderByDescending(x => x.Metadata.DateAdded).FirstOrDefault())
.ToListAsync();
Short answer:
No way. GroupBy has limitation: after grouping only Key and Aggregation result can be selected. And you are trying to select SomeLongList and full entity Customer.
Best answer:
It can be done by the SQL and ROW_NUMBER Window function but without SomeLongList
Workaround:
It is because it is not effective
var groupingQuery =
from c in DbContext.Set<Customer>()
group c by new { c.CustomerNumber } into g
select new
{
g.Key.CustomerNumber,
DateAdded = g.Max(x => x.DateAdded)
};
var query =
from c in DbContext.Set<Customer>().Include(x => x.SomeLongList)
join g in groupingQuery on new { c.CustomerNumber, c.DateAdded } equals
new { g.CustomerNumber, g.DateAdded }
select c;
var result = await query.ToListAsync();
I am trying to get a list of a database table called oracleTimeCards whose employee id equals to the employeeID in employees list. Here is what I wrote:
LandornetSQLEntities db = new LandornetSQLEntities();
List<OracleEmployee> employees = db.OracleEmployees.Where(e => e.Office.Contains(officeName) && e.IsActive == true).Distinct().ToList();
var oracleTimeCards = db.OracleTimecards.Where(c => employees.Any(e => c.PersonID == e.PersonID)).ToList();
Anyone has any idea?
I'm going to assume you're using Entity Framework here. You can't embed calls to arbitrary LINQ extension methods inside your predicate, since EF might not know how to translate these to SQL.
Assuming you want to find all the timecards for the employees you found in your first query, you have two options. The simplest is to have a navigation property on your Employee class, named let's say TimeCards, that points to a collection of time card records for the given employee. Here's how that would work:
var oracleTimeCards = employees
.SelectMany(e => e.TimeCards)
.ToList();
If you don't want to do this for whatever reason, you can create an array of employee IDs by evaluating your first query, and use this to filter the second:
var empIDs = employees
.Select(e => e.PersonID)
.ToArray();
var oracleTimeCards = db.OracleTimecards
.Where(tc => empIDs.Contains(tc.PersonID))
.ToList();
I am trying to select multiple columns from an entity object but I want 1 property to be distinct. I am very new to both LINQ and Entity Framework so any help will be useful.
Here is my LINQ query so far:
var listTypes = (from s in context.LIST_OF_VALUES
orderby s.SORT_INDEX
select new { s.LIST_TYPE, s.DISPLAY_TEXT });
I want s.LIST_TYPE to be distinct. I figure using the groupby keyword is what I want (maybe?) but I have not found a way to use it that works.
Thank you.
Assuming DISPLAY_TEXT matches LIST_TYPE somehow (so you don't lose any information):
var distinct = context.LIST_OF_VALUES
.OrderBy(s => s.SORT_INDEX)
.GroupBy(s => s.LIST_TYPE)
.Select(g => new { g.Key, g.First().DISPLAY_TEXT });
Suppose I have three tables:
Person(pid, ...)
PersonAddress(pid, aid,...)
Address(aid, ...)
Then I want to get the person address like sql:
select a.* from address a join PersonAddress pa on a.addressID=pa.addressID
where pa.personID = myPersonID
Use Entity Framework to create Entity model, then want to write a linq equivalent as above sql.
I tried it in following way:
var addresses = this.GetAddress();
var personaddresses = this.GetPersonAddress();
var query = from ad in addresses
from pa in personaddresses
where ((ad.AddressID == pa.AddressID)&&(pa.PersonID==person.personID))
select ad;
but I got error. Or I try to start from:
var result = this.Context.Address;
var result = result.Join .... //how to write linq in this way?
How to write the linq?
This is untested but if you have all of your relationships setup and you create the model (I have used Model as the name for this) from this you should be able to use the following:
var values = this.Model.Address.Select(a => a.PersonAddress.Where(pa => pa.Id == myPersonID));
You almost never use join in LINQ to Entities.
Try:
var q = from p in Context.People
where p.PersonId == personId
from a in p.Addresses // presumes p.Addresses is 1..*
select a;
Assuming you have three entities: Person, PersonAddress and Address, here is a query that should meet your needs (this example assumes an Entity Framework context named context):
var values = context.PersonAddress.Where(pa => pa.Person.PersonId == myPersonId).Select(pa => pa.Address);
However, if the PersonAddress table exists as a pure many-to-many relationship table (i.e. contains only keys), you'd be better off setting up your Entity Framework model in such a way that the intermediate table isn't necessary, which would leave you with the much simpler:
var values = context.Person.Where(p => p.PersonId == myPersonId).Addresses;
Based on the additional feedback
Because you need to include the country table, you should originate your query from the Address table. In that case:
var values = context.Address.Where(a => a.PersonAddress.Where(pa => pa.Product.Id == myProductId).Count() > 0)
To include the Country table in the result:
var values = context.Address.Include("Country").Where(a => a.PersonAddress.Where(pa => pa.Product.Id == myProductId).Count() > 0)