I want to create some test cases for Entity Framework queries that surely generate SQL commands that contain CROSS APPLY or OUTER APPLY operators.
Could someone show typical scenarios where these kind of SQL queries appear?
In LINQ 2 SQL this always results in an APPLY:
from t1 in tab1
from t2 in tab2.Where(t2 => t2.SomeCol == t1.SomeCol).Take(1)
select new { t1, t2 }
In EF this will either fail, or also result in an APPLY (I don't know which one). This is a correlated join which requires an APPLY on the SQL side.
Something like this would generate an outer apply:
var ListLocation = from d in dc.Department
select new DepartmentViewModel()
{
LocationID = d.LocationID,
ManagerName = d.Managers.FirstOrDefault(p => p.ManagerId == id).Name
};
If it doesn't work you can always pass your own query if you're using EF:
var q2 = context.Departments.SqlQuery("Select ...");
Remember though that your provider has to be SQL Server 2005 and higher, EF does not support OUTER APPLY for Oracle
Related
I am trying to recreate a query that was done in MS Access, and now is being handled in a SQL Server environment. I understand that some of the SQL syntax is different in Access than it is in SQL Server. Is there somewhere online that points out the main differences, or will help translate one to the other?
This is a query that I need to update to use in SQL Server:
UPDATE
dbo.TPR00100
INNER JOIN (
dbo.UPR10302
LEFT JOIN dbo.B3980280 ON dbo.TPR10302.COMPTRNM = dbo.B3980280.COMPTRNM
) ON dbo.TPR00100.STAFFID = dbo.TPR10302.STAFFID
SET
dbo.B3980280.COMPTRNM = dbo.TPR10302.comptrnm,
dbo.B3980280.BI_LOC_ID = dbo.TPR00100.locatnid
WHERE
(((dbo.B3980280.COMPTRNM) Is Null))
What are they key aspects that need to be handled differently in a SQL Server transaction for this query?
If find it handy to use an updateable CTE for this:
with cte as (
select
b39.comptrnm b39_comptrnm
b39.bssi_loc_id b39_bssi_loc_id,
tpr.comptrnm tpr_comptrnm,
tpr.locatnid tpr_locatnid
from dbo.tpr00100 tpr
inner join dbo.upr10302 upr on tpr.staffid = upr.staffid
inner join dbo.b3980280 b39 on tpr.comptrnm = b39.comptrnm
where b39_comptrnm is null
)
update cte
set b39_comptrnm = tpr_comptrnm, b39_bssi_loc_id = tpr_locatnid
Note: I am not really sure why the table to update is left joined in the original query, so I turned it to an `inner join .
I'm fairly new to using Linq in C# and I just want to know how a normal SQL statement will look like when compared to a Linq query?
I have this statement:
var query =
from b in db.Employee.Include(o => o.Position)
where b.Position.Position_Desc == "Junior" && b.Employee_ID == 5
select b;
So my actual question is how will this statement look if I were to write it in SQL?
query.ToString() should return the SQL.
Or you can use LinqPad
If there is a relation between Employees and Positions tables with foreign key say Employees.PositionId -> Positions.Id. Then you can use LEFT JOIN to write a similar SQL query:
SELECT Employees.*,
Positions.*
FROM Employees
LEFT JOIN Positions ON Employees.PositionId = Positions.Id
WHERE Positions.Position_Desc = 'Junior'
AND Employees.Employee_ID = 5
You can check your query in debug mode (see attach image)
Hey guys I am new in Linq and I am trying to convert stored procedures. But I am having a hard time writing update query in LINQ my query in SP is like
UPDATE #tempTable1
SET someColumn = 1
FROM #tempTable1 p, #tempTable2 t2, NonTempTable nt
WHERE t1.id = t2.id
AND t1.id = nt.id
AND nt.status = 'abcd';
I wrote following conversion of above query in LINQ
var Obj = (from t1 in temp1
join t2 in tmp2 on t1.id equals t2.id
join nt in NonTempTable on t2.id equals nt.id
where nt.status == "abcd"
select t1).First();
Obj.somecolumn = 1;
Obj.SubmitChanges();
But I am gettimg following error
Property or indexer 'AnonymousType#1.ProcedureID' cannot be assigned to -- it is read only
I just have database of my application and I am trying to convert stored procedures into LINQ using LINQPad
Can anyone tell me how to write above query to Linq? What more do I need to do this?
You have to create an entity from your tempTable1, tempTable2 and NonTempTable. Then you should be able to work with the data from these tables by means of Linq. See http://msdn.microsoft.com/en-us/data/ff830362.aspx how to create models.
After you create it, you can update your records or proper record and save changes to database
var result = (from row in model.JoinedTable
where row.status == "abcd"
select row).First();
result.someColumn = "1";
model.SaveChanges();
Linq is for querying, not updating. In order to update data you need to choose a framework (or find out what the main project team is using) that is designed to do that - Entity Framework, LinqToSQL, or plain old ADO.NET (SQlCommand + SqlConnection, etc.).
There is no built-in mechanism within Linq to update data in memory, let alone propagate changes to a data source. Even with Entity Framework - you can use Linq to get the object(s) you want to update, but the actual updating does not use Linq at all, just property setters and methods like SaveChanges() which you have in your example.
Finally found a workaround for my above question which is following
var Obj = (from t1 in temp1
join t2 in tmp2 on t1.id equals t2.id
join nt in NonTempTable on t2.id equals nt.id
where nt.status == "abcd"
select t1).First();
var anatherObj = (from o in Obj
select new { o.nonUpdatedColumn1, o.nonUpdatedColumn2, o.nonUpdatedColumn3, o.someColumn = 1});
And got the updated temporary table in "anatherObj"
My apologies for my recent SQL/Linq questions, but i need to know what this working SQL query would look like in LINQ?
select *
from CarePlan c
outer apply (select top 1 * from Referral r
where
r.CarePlanId = c.CarePlanId order by r.ReferralDate desc) x
left outer join Specialist s on s.SpecialistId = x.SpecialistId
left outer join [User] u on u.UserId = s.UserId
This basically retrieves a list of Careplans with the newest Referral (if it exists), then joins the Specialist and User table based on any found Referrals
Thanks
Kind advice: target on what you want to express in the environment of your class model and LINQ, in stead of trying to reproduce SQL. If you do something like
context.CarePlans
.Select(cp => new { Plan = cp, FirstReferral = cp.Referrals.FirstOrDefault() }
(provided that it matches your context and ignoring ordering and other joins for clarity)
It would basically do what you want, but it may very well translate to an inline subquery, rather than an OUTER APPLY. To the same effect. And the execution plan probably won't differ very much.
How can I convert this below code from SQL to Linq
SELECT CF.CustomerProfileId,CF.Salutation,CF.Gender,CF.LastName,
CF.DateOfBirth,AD.Line1,AD.Line2,AD.Line3,AD.Line4,AD.Line5,
AD.Country,AD.ElectronicAddressDesc,NCIType.NationalCustomerIdentifierTypeDesc,
NCI.NationalCustomerIdentifier from CustomerProfile CF
left join Address AD on CF.CustomerProfileId = CF.CustomerProfileId
left join NationalCustomerIdentifiers NCI on CF.CustomerProfileId = NCI.CustomerProfileId
left join NationalCustomerIdentifierType NCIType on NCI.NationalCustomerIdentifierTypeId = NCIType.NationalCustomerIdentifierTypeId
where CF.CustomerProfileId = #CustomerProfileid and CF.Version = #Version
You need to make several left joins in LINQ. This is possible though will look not very good (linq is not very comfortable when dealing with joins other than inner).
Here is a microsoft example of left join in linq It only joins two tables but you can extend it. And if you don't like how the result looks - than make a view or an sproc.