ASP.NET MVC 5 Entity Join - c#

I'm new in ASP, Entity and lambda expressions. How can I join two tables?
Route Model:
public partial class Route
{
public Route()
{
Flights = new HashSet<Flight>();
}
public int RouteID { get; set; }
public int DepartureAirportID { get; set; }
public int ArrivalAirportID { get; set; }
public int FlightDuration { get; set; }
public virtual Airport Airport { get; set; }
public virtual Airport Airport1 { get; set; }
public virtual ICollection<Flight> Flights { get; set; }
}
Airport Model:
public partial class Airport
{
public Airport()
{
Routes = new HashSet<Route>();
Routes1 = new HashSet<Route>();
}
public int AirportID { get; set; }
public string City { get; set; }
public string Code { get; set; }
public virtual ICollection<Route> Routes { get; set; }
public virtual ICollection<Route> Routes1 { get; set; }
}
SQL query looks like this:
SELECT a.AirportID, a.City
FROM Route r INNER JOIN Airport a ON r.ArrivalAirportID = a.AirportID
WHERE r.DepartureAirportID = #departureAirportID
ORDER BY a.City
Sorry for this easy question but I don't know how to do this with Entity Framework...

Something like this should do (untested and just going on from your query) with a variable hard-coded):
using (var db = new YourDbContext())
{
var query = from r in db.Route
join a in db.Airport a on r.ArrivalAirportID equals a.AirportID
where r.DepartureAirportID = 1 // replace with your varialble.
orderby a.City
select a;
}

Include with join entity framework. here doctorSendAnswerModel also a inner table.
var data = _patientaskquestionRepository.Table.Include(x=>x.DoctorSendAnswer).Join(_patientRepository.Table, a => a.PatientId, d => d.Id, (a, d) => new { d = d, a = a }).Where(x => x.a.DoctorId == doctorid);
if(!string.IsNullOrEmpty(status))
data=data.Where(x=>x.a.Status==status);
var result = data.Select(x => new {x= x.a,y=x.d }).ToList();
var dt = result.Select(x => new PatientAskQuestionModel()
{
PatientId = x.x.PatientId.Value,
AskQuestion = x.x.AskQuestion,
Id = x.x.Id,
DoctorId = x.x.DoctorId,
FileAttachment1Url = x.x.FileAttachment1,
DocName = x.y.FirstName + " " + x.y.LastName,
CreatedDate = x.x.CreatedDate.Value,
doctorSendAnswerModel = x.x.DoctorSendAnswer.Select(t => new DoctorSendAnswerModel { Answer = t.Answer }).ToList()
}).ToList();
return dt;

LinQ query:
from r in context.Route
join a in context.Airport
on r.ArrivalAirportID equals a.AirportID
WHERE r.DepartureAirportID = "value"
ORDER BY a.City
select a.AirportID, a.City

var balance = (from a in context.Airport
join c in context.Route on a.ArrivalAirportID equals c.AirportID
where c.DepartureAirportID == #departureAirportID
select a.AirportID)
.SingleOrDefault();

You can do the following:
var matches = from a in context.Airports
join r in context.Routes
on a.AirportID equals r.ArrivalAirportID
where r.DepartureAirportID = departureAirportID
order by a.City
select new
{
a.AirportID,
a.City
};

Entity query with conditional join with pagination.
if (pageIndex <= 0)
pageIndex = 1;
pageIndex = ((pageIndex - 1) * pageSize) ;
var patient = _patientRepository.Table.Join(_DoctorPatient.Table.Where(x => x.DoctorId == Id && x.IsBlocked==false), x => x.Id, d => d.PatientId, (x, d) => new { x = x });
if (state != "")
patient = patient.Where(x => x.x.State.Contains(state));
if (name != "")
patient = patient.Where(x => (x.x.FirstName + x.x.LastName).Contains(name));
if (sdate != null)
patient = patient.Where(x => x.x.CreatedDate >= sdate);
if (eDate != null)
patient = patient.Where(x => x.x.CreatedDate <= eDate);
var result = patient.Select(x => x.x).Select(x => new PatientDoctorVM() { PatientId = x.Id, Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, SSN = x.NewSSNNo, UserProfileId = x.UserProfileId, Email = x.Email, TumbImagePath = x.TumbImagePath }).OrderBy(x => x.Id).Skip(pageIndex).Take(pageSize).ToList();

Your entity and lembda query will be lool like this:
return (from d in _doctorRepository.Table
join p in _patientDoctor.Table on d.Id equals p.DoctorId
where p.PatientId == patientid.Value select d
).ToList();

Take a look at this site, it will explain you how the join works in Linq.
So if you ever need it again you will be able to solve it yourself.

Related

C# how to achieve 'group by' 'left join' and list inside a list selection in linq

var products = from P in product.GetAllAsync().Result
join PV in
_repositoryVariation.GetAllAsync().Result on P.Id equals PV.ProductId
into PVLJ
from PV in PVLJ.DefaultIfEmpty()
select new ProductwithVarientsGroupDto
{
Label = P.ProductName,
ProductId = P.Id,
Items = new List<ProdcutVariantsdto>() { new ProdcutVariantsdto { Label = P.ProductName.ToString() + (PV == null ? "" : " (" + PV?.VariantName.ToString() + ")"), ProductId = P.Id, ProdVariantId = PV?.Id > 0 ? PV?.Id : 0 } }
//here i need to add multiple variant records to Items, now it
// showing each item as a separate row data
};
var result = products.ToList();
return result;
The following query will work. After you left joined the data, just switch to client-evaluation (using AsEnumerable() or ToList()) and do the actual grouping with Linq. EF Core will not be able to do a Linq style grouping on its own and the data is being retrieved anyway, so there is no downside doing it client-side:
var products = (from p in context.Products
join v in
context.ProductVariations on p.Id equals v.ProductId
into g
from v in g.DefaultIfEmpty()
select new {product = p, variation = v})
.AsEnumerable() // <-- switch to client-evaluation
.GroupBy(g => g.product, g => g.variation)
.Select(g => new ProductwithVarientsGroupDto
{
Label = g.Key.ProductName,
ProductId = g.Key.Id,
Items = g.Select(v => new ProdcutVariantsdto()
{
Label = g.Key.ProductName + (v == null
? ""
: " (" + v.VariantName.ToString() + ")"),
ProductId = g.Key.Id,
ProdVariantId = v.Id > 0
? v.Id
: 0
}).ToList()
});
As #PanagiotisKanavos already mentioned in the comments, your original code first retrieves all entities from the database and then executes your query on them in memory. If you want to keep doing that, just replace context.Products with product.GetAllAsync().Result and context.ProductVariations with _repositoryVariation.GetAllAsync().Result. You could then also drop the AsEnumerable(), because you are already processing the query client-side.
Here is the fully working sample console project I used for testing:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace IssueConsoleTemplate
{
public class Product
{
public int Id { get; set; }
public string ProductName { get; set; }
}
public class ProductVariation
{
public int Id { get; set; }
public int ProductId { get; set; }
public string VariantName { get; set; }
}
public class ProductwithVarientsGroupDto
{
public string Label { get; set; }
public int ProductId { get; set; }
public List<ProdcutVariantsdto> Items = new List<ProdcutVariantsdto>();
}
public class ProdcutVariantsdto
{
public string Label { get; set; }
public int ProductId { get; set; }
public int? ProdVariantId { get; set; }
}
public class Context : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<ProductVariation> ProductVariations { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(
#"Data Source=.\MSSQL14;Integrated Security=SSPI;Initial Catalog=So63031344")
.UseLoggerFactory(
LoggerFactory.Create(
b => b
.AddConsole()
.AddFilter(level => level >= LogLevel.Information)))
.EnableSensitiveDataLogging()
.EnableDetailedErrors();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().HasData(
new Product {Id = 1, ProductName = "Car"},
new Product {Id = 2, ProductName = "Bus"});
modelBuilder.Entity<ProductVariation>().HasData(
new ProductVariation {Id = 1, ProductId = 1, VariantName = "Minivan"},
new ProductVariation {Id = 2, ProductId = 1, VariantName = "Convertible"},
new ProductVariation {Id = 3, ProductId = 2, VariantName = "Public Transportation"},
new ProductVariation {Id = 4, ProductId = 2, VariantName = "Shuttle"});
}
}
internal static class Program
{
private static void Main()
{
using var context = new Context();
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var products = (from p in context.Products
join v in
context.ProductVariations on p.Id equals v.ProductId
into g
from v in g.DefaultIfEmpty()
select new {product = p, variation = v})
.AsEnumerable()
.GroupBy(g => g.product, g => g.variation)
.Select(g => new ProductwithVarientsGroupDto
{
Label = g.Key.ProductName,
ProductId = g.Key.Id,
Items = g.Select(v => new ProdcutVariantsdto()
{
Label = g.Key.ProductName + (v == null
? ""
: " (" + v.VariantName.ToString() + ")"),
ProductId = g.Key.Id,
ProdVariantId = v.Id > 0
? v.Id
: 0
}).ToList()
});
var result = products.ToList();
Debug.Assert(result.Count == 2);
Debug.Assert(result[0].ProductId == 1);
Debug.Assert(result[0].Items.Count == 2);
Debug.Assert(result[0].Items[0].ProdVariantId == 1);
}
}
}

How to provide SQL subquery in LINQ

What is the best practice to convert Sub Query into LINQ,
for example I use this following query :
select VerID = (select top 1 x.INTERNALPACKINGSLIPID from
CUSTPACKINGSLIPVERSION x where a.RECID = x.CUSTPACKINGSLIPJOUR
order by x.VERSIONDATETIME desc),
c.LINENUM, c.RECID, *
from CUSTPACKINGSLIPJOUR a inner join CUSTPACKINGSLIPTRANS c
on a.PACKINGSLIPID = c.PACKINGSLIPID
I simulated you database with classes to get the syntax correct. Make modifications as necessary. There is no best method. Some people like using Where instead of joins. I like joins.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<CUSTPACKINGSLIPVERSIONs> CUSTPACKINGSLIPVERSION = new List<CUSTPACKINGSLIPVERSIONs>();
List<CUSTPACKINGSLIPJOURs> CUSTPACKINGSLIPJOUR = new List<CUSTPACKINGSLIPJOURs>();
List<CUSTPACKINGSLIPTRANSs> CUSTPACKINGSLIPTRANS = new List<CUSTPACKINGSLIPTRANSs>();
var VerId = (from vId in CUSTPACKINGSLIPVERSION
join slipId in CUSTPACKINGSLIPJOUR on vId.INTERNALPACKINGSLIPID equals slipId.RECID
join cId in CUSTPACKINGSLIPTRANS on vId.INTERNALPACKINGSLIPID equals cId.PACKINGSLIPID
select new { vid = vId, slipId = slipId, cId = cId })
.GroupBy(x => x.vid.VERSIONDATETIME)
.OrderBy(x => x.Key)
.FirstOrDefault()
.Select(x => new { linenum = x.cId.LINENUM, recid = x.cId.RECID })
.ToList();
}
}
public class CUSTPACKINGSLIPVERSIONs
{
public int INTERNALPACKINGSLIPID { get; set; }
public DateTime VERSIONDATETIME { get; set; }
}
public class CUSTPACKINGSLIPJOURs
{
public int RECID { get; set; }
public int PACKINGSLIPID { get; set; }
}
public class CUSTPACKINGSLIPTRANSs
{
public int PACKINGSLIPID { get; set; }
public int LINENUM { get; set; }
public int RECID { get; set; }
}
}
You have this in your query and I am assuming it is a typo: a.RECID = x.CUSTPACKINGSLIPJOUR because CUSTPACKINGSLIPJOUR is the collection name. Therefore, I used SomeId instead. But this should give you the idea:
Do a subquery within the projection. You will also need to order by descending and then take the first record-this will be like top 1. Here is the query:
var query = from a in CUSTPACKINGSLIPJOUR
join c in CUSTPACKINGSLIPTRANS on a.PACKINGSLIPID equals c.PACKINGSLIPID
select new
{
VerID = (from x in CUSTPACKINGSLIPVERSION
where a.RECID == x.SomeId select x)
.OrderByDescending(o => o.VERSIONDATETIME)
.First().INTERNALPACKINGSLIPID,
c.LINENUM,
c.RECID
};
You can test it with the following collections:
var CUSTPACKINGSLIPJOUR = new List<CUSTPACKINGSLIPJOUR> { new CUSTPACKINGSLIPJOUR { PACKINGSLIPID = 1, RECID = 1 },
new CUSTPACKINGSLIPJOUR { PACKINGSLIPID = 2, RECID = 2 }};
var CUSTPACKINGSLIPTRANS = new List<CUSTPACKINGSLIPTRANS>
{
new CUSTPACKINGSLIPTRANS { LINENUM = 1, RECID = 1, PACKINGSLIPID = 1 }
};
var CUSTPACKINGSLIPVERSION = new List<CUSTPACKINGSLIPVERSION>
{
new CUSTPACKINGSLIPVERSION { INTERNALPACKINGSLIPID = 1, SomeId = 1, VERSIONDATETIME = DateTime.Today.AddDays(-1) },
new CUSTPACKINGSLIPVERSION { INTERNALPACKINGSLIPID = 2, SomeId = 1, VERSIONDATETIME = DateTime.Today }
};
It will be the same query if you use a DbSet<T>.
Suppose you have those setup:
public class TBL_CUSTPACKINGSLIPVERSION
{
public int CUSTPACKINGSLIPVERSION_ID { get; set; }
public int INTERNALPACKINGSLIPID { get; set; }
public DateTime VERSIONDATETIME { get; set; }
}
public class TBL_CUSTPACKINGSLIPJOUR
{
public int RECID { get; set; }
public int PACKINGSLIPID { get; set; }
}
public class TBL_CUSTPACKINGSLIPTRANS
{
public int PACKINGSLIPID { get; set; }
public int LINENUM { get; set; }
public int RECID { get; set; }
}
var CUSTPACKINGSLIPVERSION = new List<TBL_CUSTPACKINGSLIPVERSION>();
var CUSTPACKINGSLIPJOUR = new List<TBL_CUSTPACKINGSLIPJOUR>();
var CUSTPACKINGSLIPTRANS = new List<TBL_CUSTPACKINGSLIPTRANS>();
Then you can setting up the combined query as given in example below (assumed CUSTPACKINGSLIPVERSION_ID is the identity key which used in comparison between CUSTPACKINGSLIPJOUR & CUSTPACKINGSLIPTRANS):
var query = (from a in CUSTPACKINGSLIPJOUR
join c in CUSTPACKINGSLIPTRANS
on a.PACKINGSLIPID equals c.PACKINGSLIPID
select new {
VerID = (from x in CUSTPACKINGSLIPVERSION
where a.RECID == x.CUSTPACKINGSLIPVERSION_ID // should be an identity column/primary key to compare with
orderby x.VERSIONDATETIME descending
select x).FirstOrDefault().INTERNALPACKINGSLIPID,
c.LINENUM,
c.RECID
}).ToList();
Note that your query includes * at the end of SELECT statement which may indicate the query will return all records from both tables involved in join clause. If you want to return entire records of CUSTPACKINGSLIPJOUR only but not return all CUSTPACKINGSLIPTRANS, include a into the select new statement (incorporates SQL usage of a.*):
select new {
VerID = (from x in CUSTPACKINGSLIPVERSION
where a.RECID == x.CUSTPACKINGSLIPVERSION_ID // should be an identity column/primary key to compare with
orderby x.VERSIONDATETIME descending
select x).FirstOrDefault().INTERNALPACKINGSLIPID,
c.LINENUM,
c.RECID,
a // used if you want to return all records from CUSTPACKINGSLIPJOUR
}).ToList();

Store LINQ result into view-model refereeing to multiple class objects instead of storing LINQ result in var

I have linq statement that gives three class object data
1- appForm
2- ebsSync
3- SyncAuditLog
var _AppForms2 = (from appForm in _uof.Web_AppFormsRepository.GetAll()
join syncAuditLog in (_uof.Web_SyncAuditLogRepository.GetAll().
Where(sal => sal.LOG_STATUS.Equals("EP") &&
sal.LOOKUP_ID != null &&
sal.ID == maxAuditID)
.Select(shortListedAuditLog => new { shortListedAuditLog })) on appForm.SUBMISSION_ID equals syncAuditLog.shortListedAuditLog.SUBMISSION_ID
join ebsSync in _uof.Web_EBS_SyncRepository.GetAll() on appForm.SUBMISSION_ID equals ebsSync.SUBMISSION_ID
select new {appForm , ebsSync, syncAuditLog }).ToList();
I want to store this LINQ query result into viewModel as instead of 'var _AppForms';
public class WebSyncSummaryEntity
{
public List<Web_AppFormsEntity> AppFormsEntity { get; set; }
public List<Web_EBS_SyncEntity> EBS_SyncEntity { get; set; }
public List<Web_SyncAuditLogEntity> SyncAuditLogEntity { get; set; }
}
Need to fix here!
public List<WebSyncSummaryEntity> GetWebSyncSummary()
{
List<WebSyncSummaryEntity> _AppForms = null;
using (var _uof = new UCAS_WebSync_AdminTool_UOF())
{
var maxAuditID = (from sal in _uof.Web_SyncAuditLogRepository.GetAll().Where(
sal => sal.LOG_STATUS.Equals("EP") &&
sal.LOOKUP_ID != null)
select sal).Max(x => x.ID);
_AppForms = (from appForm in _uof.Web_AppFormsRepository.GetAll()
join syncAuditLog in (_uof.Web_SyncAuditLogRepository.GetAll().
Where(sal => sal.LOG_STATUS.Equals("EP") &&
sal.LOOKUP_ID != null &&
sal.ID == maxAuditID)
.Select(shortListedAuditLog => new { shortListedAuditLog })) on appForm.SUBMISSION_ID equals syncAuditLog.shortListedAuditLog.SUBMISSION_ID
join ebsSync in _uof.Web_EBS_SyncRepository.GetAll() on appForm.SUBMISSION_ID equals ebsSync.SUBMISSION_ID
select new {appForm , ebsSync, syncAuditLog }).ToList();
var test = "d";
}
return _AppForms;
}
Change your view model
public class WebSyncSummaryEntity
{
public Web_AppFormsEntity AppFormsEntity { get; set; }
public Web_EBS_SyncEntity EBS_SyncEntity { get; set; }
public Web_SyncAuditLogEntity SyncAuditLogEntity { get; set; }
}
and then
var _AppForms2 = (from appForm in _uof.Web_AppFormsRepository.GetAll()
join syncAuditLog in (_uof.Web_SyncAuditLogRepository.GetAll().
Where(sal => sal.LOG_STATUS.Equals("EP") &&
sal.LOOKUP_ID != null &&
sal.ID == maxAuditID)
.Select(shortListedAuditLog => new { shortListedAuditLog })) on appForm.SUBMISSION_ID equals syncAuditLog.shortListedAuditLog.SUBMISSION_ID
join ebsSync in _uof.Web_EBS_SyncRepository.GetAll() on appForm.SUBMISSION_ID equals ebsSync.SUBMISSION_ID
select new WebSyncSummaryEntity {AppFormsEntity =appForm , EBS_SyncEntity =ebsSync, SyncAuditLogEntity =syncAuditLog }).ToList();
I haven't tested the code, just suggesting you a way to go, looking for better solution.

Left join multiple tables using lambda expression

I have 2 tables:
specs {specId, desc, createdby, lastupdatedby}
users {userid, username}
I want the below linq query need to be written in pure lambda expression
from spec in specs
from user in users.where(x => x.userId== spec.createdby).DefaultIfEmpty()
from updatedUser in users.where(x => x.userId== spec.lastupdatedbyby).DefaultIfEmpty()
select new {
spec = spec
user = user,
updatedUser = updatedUser
}
Please assist.
Data would be like say:
spec[{1, test, 1234, 2345},{2, test1, 1234, null}]
users[{1234, Allen},{2345, Dwayne}]
So the result should be
[{1, test, Allen, Dwayne}, {2, test1, Allen, null}]
Let's start with these classes:
class Specs {
public int specId { get; set; }
public string desc { get; set; }
public int createdby { get; set; }
public int lastupdatedby { get; set; }
}
class Users {
public int userId { get; set; }
public string username { get; set; }
}
class UpdatedUser {
public int userId {get; set;}
public string username { get; set; }
}
Now the Linq query, for convenience I have created some example data:
var specs = new Specs[]
{
new Specs{specId = 1, desc = "Spec1", createdby=1, lastupdatedby=1},
new Specs{specId = 2, desc = "Spec2", createdby=2, lastupdatedby=3},
new Specs{specId = 3, desc = "Spec3", createdby=3, lastupdatedby=1},
new Specs{specId = 4, desc = "Spec4", createdby=3, lastupdatedby=3},
};
var user = new Users[]
{
new Users{userId = 1, username = "User1"},
new Users{userId = 2, username = "User2"},
};
var updatedUser = new UpdatedUser[]
{
new UpdatedUser{userId = 1, username = "UpdatedUser1"},
new UpdatedUser{userId = 2, username = "UpdatedUser2"},
};
var result = specs
.GroupJoin(user,
s => s.createdby,
u => u.userId,
(s, u) => u.Select(x => new {spec = s, user = x})
.DefaultIfEmpty(new {spec = s, user = (Users)null}))
.SelectMany(g => g)
.GroupJoin(updatedUser,
firstJoin => firstJoin.spec.lastupdatedby,
uu => uu.userId,
(firstJoin, uu) =>
uu.Select(y => new {spec = firstJoin.spec, user = firstJoin.user, updatedUser = y})
.DefaultIfEmpty(new {spec = firstJoin.spec, user = firstJoin.user, updatedUser = (UpdatedUser) null}))
.SelectMany(g1 => g1)
.ToList();
The GroupJoin extension method help you obtain a tuple with all the elements of the starting table with a list of elements of the joined table.
Now if you enumerate the results:
result.ForEach(item => {
Console.WriteLine(item.spec.desc);
Console.WriteLine(item.user != null ? item.user.username : "NULL");
Console.WriteLine(item.updatedUser != null ? item.updatedUser.username : "NULL");
Console.WriteLine();
});
You obtain this:
Spec1
User1
UpdatedUser1
Spec2
User2
NULL
Spec3
NULL
UpdatedUser1
Spec4
NULL
NULL
You can try
var list = specs.Join(users,
s => s.lastupdatedby,
u => u.userid,
(s, u) => new { specs = s, users = u })
.Select(x => new {
specId = x.specs.specId,
desc = x.specs.desc,
createdby=x.specs.createdby,
username=x.users.username
}).ToString();
LEFT JOIN MULTIPLE TABLES
------------------------
create table Rama(rid int,name varchar(80),zip int);
create table Kris(kid int,rid int, Title varchar(80),zip int);
insert into Rama values(1,'Robert Rama' ,10001),
(2,'Roger Raju' ,10002),
(3,'Kevin Kali' ,10003),
(4,'Mark Mutu' ,10004)
insert into Kris values(0,0,'NP' ,10001),
(1,1,'VP' ,10001),
(2,2,'AVP',10002)
//Lambda expression
//Download https://www.linqpad.net/Download.aspx
//Create tables as given below and connect linqpad to your db
//select C# statement(s) on linqpad and run below
var v =
from r in Ramas
join k in Kris
on new { r.Rid, r.Zip } equals new { k.Rid, k.Zip }
into resultGroups
from k in resultGroups.DefaultIfEmpty()
select new { r.Rid, r.Name, k.Title };
v.Dump();

How to write Lambda expression for this SQL query?

I have the following SQL query
Select cLedgerName,dDateFrom,cPeriodType,nPeriodFrom,nPeriodTo
from sys_Account_Ledger a,sys_Log_Deposits_Interest_Master b
where a.cGLCode=b.cGLCode and b.dDateFrom='08-11-2012' and b.cPeriodType='Days'
I wanted to write this query using Lambda expression.This is where I am stuck.
public IList<ListViewData> GetDepositsListViewData(string glCode, string effectDate, string periodType)
{
using (var db = new DataClasses1DataContext())
{
var data=db.sys_Account_Ledgers.Join(db.sys_Log_Deposits_Interest_Masters,
ledger=>ledger.cGLCode,
deposits=>deposits.cGLCode,
(ledger,deposits)=>new {db.sys_Account_Ledgers =ledger,db.sys_Log_Deposits_Interest_Masters =deposits})
}
}
I have created a class which will be the return type of my query.
Here is the class
public class ListViewData
{
public string LedgerName { get; set; }
public string DateFrom { get; set; }
public string PeriodType { get; set; }
public int PeriodFrom { get; set; }
public int PeriodTo { get; set; }
}
Can anyone help me out with the lambda expression?
var result = dataContext.SysAccountLedger
.Join(dataContext.SysLogDepositsInterestMaster,
a => a.cGlCode,
b => b.cGlCode,
(a, b) => new ListViewData
{
LedgerName = a.LedgerName,
DateFrom = b.DateFrom,
PeriodType = b.PeriodType
// other properties
})
.Where(item => item.DateFrom = Convert.ToDateTime("08-11-2012") &&
item.PeriodType == "Days")
.ToList();
//Direct translation into Linq:
var query = from a in db.sys_Account_Ledger
join b in db.sys_Log_Deposits_Interest_Master on a.cGLCode equals b.cGLCode
where b.dDateFrom == Convert.ToDateTime("08-11-2012") && b.cPeriodType == "Days"
select new { a, b };
//Lambda of this:
var query = db.sys_AccountLedger
.Join(db.sys_Log_Deposits_Interest_Master,
a => a.cGLCode,
b => b.cGLCode,
(a, b) => new {a , b})
.Where(w => w.dDateFrom == Convert.ToDateTime("08-11-2012") && w.cPeriodType == "Days");

Categories