Create a cycle in T-SQL from the list - tsql

I have code written in C#, but I want to create a T-SQL script to run on the server. This is part of my C# code that I want to convert to T-SQL:
var enumerator = distinctlist.GetEnumerator();
while (enumerator.MoveNext())
{
mtbn dtb = enumerator.Current as mtbn;
var user = users.Where(x => x.Name == dtb.UserNameTb).FirstOrDefault();
var action = actions.Where(x => x.Name == dtb.ActionTb.Value.ToString()).FirstOrDefault();
var project = projects.Where(x => x.Name == dtb.ProjectNameTb).FirstOrDefault();
var transaction = transactions.Where(x => x.Name == dtb.TransactioNameTb).FirstOrDefault();
TransactBoard transactBoard = dbContext.TransactBoard.Add(new TransactBoard
{
User = user != null ? user : new EF.User { Name = dtb.UserNameTb },
Action = action != null ? action : new EF.Action { Name = dtb.ActionTb.Value.ToString() },
Project = project != null ? project : new Project { Name = dtb.ProjectNameTb, Path = #"S:\\xxxx\\" + dtb.ProjectNameTb },
Transaction = transaction != null ? transaction : new Transaction { Name = dtb.TransactioNameTb },
DateTime = dtb.WriteDateTimeTb.Value
});
dbContext.MonitorControl.Add(
new MonitorControl
{
ElementId = dtb.ElementIdTb.Value,
Category = category.Where(x => x.Id == dtb.CategoryIdTb).FirstOrDefault(),
TransactBoard = transactBoard
});
}
This is what I did on T-SQL:
begin tran
insert dbo.TransactionBoard(TrancationId, UserId, ActionId, ProjectId, [DateTime] )
select t.Id as TrancationId, u.Id as UserId, s.ActionTb, p.Id as ProjectId, s.WriteDateTimeTb
from monitorControlDb.dbo.MonitorlControlTable s
left join dbo.[Transaction] t
on t.[Name] = s.TransactioNameTb
left join dbo.[User] u
on u.[Name] = s.UserNameTb
left join dbo.Project p
on p.[Name] = s.ProjectNameTb
insert dbo.MonitorControl(ElementId, CategoryId)
select s.ElementIdTb, s.CategoryIdTb
from monitorControlDb.dbo.MonitorlControlTable s
commit

Related

Upgraded to .NET Core 3.1 and receiving an error in a LINQ query related to using .FirstOrDefault()

I have an Entity Framework controller that has been using the method below successfully. However I recently updated my project to use .NET Core 3.1 and it must've broken something.
I am now getting this error:
FirstOrDefault()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()
I did some research, and some people say not to use GroupBy extension which I do in the query below. I tried to take it out, but that just generates more errors.
I also went to this:
But I couldn't figure out how to fix my complex query below.
Honestly, I'm not sure why it's failing or how to properly fix it.
Does anyone see anything wrong?
Thanks!
public async Task<ActionResult<object>> GetStarChemicalData(string starID)
{
var starChemicalData = await (from starlist in _context.StarList
join ql in _context.ChemicalList on starlist.ChemicalId equals ql.ChemicalId into stars
from chemicallist in stars.DefaultIfEmpty()
join qc in _context.ChemicalAtoms on chemicallist.ChemicalId equals qc.ChemicalId into chemicals
from chemicalatoms in chemicals.DefaultIfEmpty()
join nk in _context.StarLinks on chemicalatoms.AtomId equals nk.AtomId into links
from starlinks in links.DefaultIfEmpty()
where starlist.StarId == starID
select new
{
StarId = starlist.StarId,
StarType = starlist.StarType,
StarTitle = starlist.StarTitle,
ChemicalId = starlist.ChemicalId,
AtomId = (Guid?)chemicalatoms.AtomId,
OrderId = chemicalatoms.OrderId,
ChemicalText = chemicallist.ChemicalText,
AtomText = chemicalatoms.AtomText,
Wavelength = chemicalatoms.Wavelength,
isRedShifted = (starlinks.AtomId != null && starlist.StarType == 1) ? 1
: (starlinks.AtomId == null && starlist.StarType == 1) ? 0
: (int?)null
})
.GroupBy(x => x.StarId)
.Select(g => new
{
StarId = g.FirstOrDefault().StarId,
StarType = g.FirstOrDefault().StarType,
StarTitle = g.FirstOrDefault().StarTitle,
ChemicalId = g.FirstOrDefault().ChemicalId,
ChemicalText = g.FirstOrDefault().ChemicalText,
ChemicalAtoms = (g.FirstOrDefault().AtomId != null ? g.Select(x => new
{
AtomId = x.AtomId,
OrderId = x.OrderId,
AtomText = x.AtomText,
Feedback = x.Wavelength,
IsCorrect = x.isRedShifted
}) : null)
}).FirstOrDefaultAsync();
return starChemicalData;
ERROR AFTER DEBUGGING:
.Select(x => new {
AtomId = x.AtomId,
OrderId = x.OrderId,
AtomText = x.AtomText,
Feedback = x.Wavelength,
IsCorrect = x.isRedShifted
})' could not be translated.
You have alot of FirstOrDefault (s) calls.
To code them "safely", you can try this:
.FirstOrDefault() ?? string.Empty
or
.FirstOrDefault() ?? 0
..
the above is a short hand version of this: (null check + ? ternary operator) (again, this is a "safe" way to code it)
StarId = null == g.FirstOrDefault() ? 0 : g.FirstOrDefault().StarId,
StarType = null == g.FirstOrDefault() ? string.Empty : g.FirstOrDefault().StarType,
StarTitle = null == g.FirstOrDefault() ? string.Empty : g.FirstOrDefault().StarTitle,
..
But better to debug, to figure out what is wrong
Change ALL OF these (temporarilty) to "" and 0
I'm listing 3 of them, but you should change all of them
instead of this:
StarId = g.FirstOrDefault().StarId,
StarType = g.FirstOrDefault().StarType,
StarTitle = g.FirstOrDefault().StarTitle,
use (temporarily) this:
StarId = 0,
StarType = "",
StarTitle = "",
(again do ALL of them)
and one-by-one, replace them back
StarId = g.FirstOrDefault().StarId,
StarType = "",
StarTitle = "",
to find the "culprit".
Here is some pseudo code.......that you can try to use the intermediate step of IQueryable. Its pseduo code, you'll have to tweak.
IQueryable is a way to "slowly build up the query" instead of writing a single super query.......and helps with debugging. Eventually, you will comment out (or delete) ... tempDebuggingCollection ........ but it can help get you to where you want to go.
public async Task<ActionResult<object>> GetStarChemicalData(string starID)
{
IQueryable<YourObjectHere> starChemicalDataQueryable = await (from starlist in _context.StarList
join ql in _context.ChemicalList on starlist.ChemicalId equals ql.ChemicalId into stars
from chemicallist in stars.DefaultIfEmpty()
join qc in _context.ChemicalAtoms on chemicallist.ChemicalId equals qc.ChemicalId into chemicals
from chemicalatoms in chemicals.DefaultIfEmpty()
join nk in _context.StarLinks on chemicalatoms.AtomId equals nk.AtomId into links
from starlinks in links.DefaultIfEmpty()
where starlist.StarId == starID;
ICollection<YourObjectHere> tempDebuggingCollection = starChemicalDataQueryable.ToListAsync(CancellationToken.None);
var starChemicalData = starChemicalDataQueryable
select new
{
StarId = starlist.StarId,
StarType = starlist.StarType,
StarTitle = starlist.StarTitle,
ChemicalId = starlist.ChemicalId,
AtomId = (Guid?)chemicalatoms.AtomId,
OrderId = chemicalatoms.OrderId,
ChemicalText = chemicallist.ChemicalText,
AtomText = chemicalatoms.AtomText,
Wavelength = chemicalatoms.Wavelength,
isRedShifted = (starlinks.AtomId != null && starlist.StarType == 1) ? 1
: (starlinks.AtomId == null && starlist.StarType == 1) ? 0
: (int?)null
})
.GroupBy(x => x.StarId)
.Select(g => new
{
StarId = g.FirstOrDefault().StarId,
StarType = g.FirstOrDefault().StarType,
StarTitle = g.FirstOrDefault().StarTitle,
ChemicalId = g.FirstOrDefault().ChemicalId,
ChemicalText = g.FirstOrDefault().ChemicalText,
ChemicalAtoms = (g.FirstOrDefault().AtomId != null ? g.Select(x => new
{
AtomId = x.AtomId,
OrderId = x.OrderId,
AtomText = x.AtomText,
Feedback = x.Wavelength,
IsCorrect = x.isRedShifted
}) : null)
}).FirstOrDefaultAsync();
return starChemicalData;
............
AGain, same safe checks:
ChemicalAtoms = (g.FirstOrDefault().AtomId != null ? g.Select(x => new
{
AtomId = x.AtomId,
OrderId = x.OrderId,
AtomText = x.AtomText,
Feedback = x.Wavelength,
IsCorrect = x.isRedShifted
}) : null)
You are not safely checking for g.FirstOrDefault() ....
something like this:
ChemicalAtoms = null == g.FirstOrDefault() ? null : (g.FirstOrDefault().AtomId != null ? g.Select(x => new
{
AtomId = x.AtomId,
OrderId = x.OrderId,
AtomText = x.AtomText,
Feedback = x.Wavelength,
IsCorrect = x.isRedShifted
}) : null)

Dynamic Search Using Entity Framework

I have a search screen with optional fields using Entity Framework, I want to build a dynamic query without selecting the object and filter on it.
I want to Optimize the following Existing Search, I don't want to select "var query = from p in context.APLCN_TRCKR select p;" at this stage because the application will be used by more than 100 people at once:
using (var context = new VASTEntities())
{
var query = from p in context.APLCN_TRCKR select p;
if (!string.IsNullOrEmpty(searchObj.CUST_NAME_X))
query = query.Where(p => p.CUST_NAME_X == searchObj.CUST_NAME_X.Trim());
if (!string.IsNullOrEmpty(searchObj.SURNM_X))
query = query.Where(p => p.CUST_SURNM_X == searchObj.SURNM_X.Trim());
if (!string.IsNullOrEmpty(searchObj.QUEUE_ID))
query = query.Where(p => p.QUEUE_ID == searchObj.QUEUE_ID.Trim());
if (!string.IsNullOrEmpty(searchObj.BP_ID))
query = query.Where(p => p.BPID == searchObj.BP_ID.Trim());
if (!string.IsNullOrEmpty(searchObj.UserID))
query = query.Where(p => p.CURR_OWNR_USER_ID == searchObj.UserID.Trim());
if (!string.IsNullOrEmpty(searchObj.APLCN_TRCKR_ID))
query = query.Where(p => p.APLCN_TRCKR_ID == searchObj.APLCN_TRCKR_ID.Trim());
if (!string.IsNullOrEmpty(searchObj.APLCN_STTS_ID))
query = query.Where(p => p.APLCN_STTS_ID == searchObj.APLCN_STTS_ID.Trim());
if (!string.IsNullOrEmpty(searchObj.CUST_ID))
query = query.Where(p => p.CUST_ID == searchObj.CUST_ID.Trim());
if (!string.IsNullOrEmpty(searchObj.CELL_ID))
query = query.Where(p => p.CELL_ID == searchObj.CELL_ID.Trim());
if (!string.IsNullOrEmpty(searchObj.ORIGN_ID))
query = query.Where(p => p.ORIGN_ID == searchObj.ORIGN_ID.Trim());
if (!string.IsNullOrEmpty(searchObj.ORGTN_CHANL_ID))
query = query.Where(p => p.ORGTN_CHANL_ID == searchObj.ORGTN_CHANL_ID.Trim());
if (!string.IsNullOrEmpty(searchObj.CR_DCSN_ID))
query = query.Where(p => p.CR_DCSN_ID == searchObj.CR_DCSN_ID.Trim());
if (!string.IsNullOrEmpty(searchObj.SBSA_CUST_I))
query = query.Where(p => p.SBSA_CUST_I == searchObj.SBSA_CUST_I.Trim());
if (!string.IsNullOrEmpty(searchObj.USER_ID_APP_CRTD))
query = query.Where(p => p.USER_ID_APP_CRTD == searchObj.USER_ID_APP_CRTD.Trim());
if (!string.IsNullOrEmpty(searchObj.RGION_ID))
{
int r = int.Parse(searchObj.RGION_ID.Trim());
query = query.Where(p => p.RGION_ID == r);
}
if (!string.IsNullOrEmpty(searchObj.CR_REGION))
{
int x = int.Parse(searchObj.CR_REGION);
if (x == 0)
{
// check 0 - not applicable or null
query = query.Where(p => p.CR_REGION_ID == 0 || p.CR_REGION_ID == null);
}
else
{
query = query.Where(p => p.CR_REGION_ID == x);
}
}
if (!string.IsNullOrEmpty(searchObj.Process_Type))
query = query.Where(p => p.PRCES_TYPE_ID == searchObj.Process_Type.Trim());
query.ToList();
foreach (var a in query)
{
searchAppsObj.Add(Translator.TranslateReqObjToBO.TranslateDTOToSearchApp(a));
}
if (query.Count() == 0)
{
throw new Exception("No Applications Found.");
}
context.Connection.Close();
return searchAppsObj;
}
I want to do something like this but this one is not working properly:
string cust_name_x = "", surname_x = "", queue_id = "", bp_id = "", user_id = "", aplcn_trckr_id = "",
aplcn_stts_id = "", cust_id = "", process_type = "", cr_region = "", cell_id = "", Origin = "", region = "", channel = "", credit_verdict = "", sbsa_cust_id = "", app_creator_id = "";
if (!string.IsNullOrEmpty(searchObj.CUST_NAME_X))
cust_name_x = searchObj.CUST_NAME_X.Trim();
if (!string.IsNullOrEmpty(searchObj.SURNM_X))
surname_x = searchObj.SURNM_X.Trim();
if (!string.IsNullOrEmpty(searchObj.QUEUE_ID))
queue_id = searchObj.QUEUE_ID.Trim();
if (!string.IsNullOrEmpty(searchObj.BP_ID))
bp_id = searchObj.BP_ID;
if (!string.IsNullOrEmpty(searchObj.UserID))
user_id = searchObj.UserID.Trim();
if (!string.IsNullOrEmpty(searchObj.APLCN_TRCKR_ID))
aplcn_trckr_id = searchObj.APLCN_TRCKR_ID.Trim();
if (!string.IsNullOrEmpty(searchObj.APLCN_STTS_ID))
aplcn_stts_id = searchObj.APLCN_STTS_ID.Trim();
if (!string.IsNullOrEmpty(searchObj.CUST_ID))
cust_id = searchObj.CUST_ID.Trim();
if (!string.IsNullOrEmpty(searchObj.Process_Type))
process_type = searchObj.Process_Type.Trim();
if (!string.IsNullOrEmpty(searchObj.CR_REGION))
cr_region = searchObj.CR_REGION.Trim();
if (!string.IsNullOrEmpty(searchObj.CELL_ID))
cell_id = searchObj.CELL_ID.Trim();
if (!string.IsNullOrEmpty(searchObj.ORIGN_ID))
Origin = searchObj.ORIGN_ID.Trim();
if (!string.IsNullOrEmpty(searchObj.RGION_ID))
region = searchObj.RGION_ID.Trim();
if (!string.IsNullOrEmpty(searchObj.ORGTN_CHANL_ID))
channel = searchObj.ORGTN_CHANL_ID.Trim();
if (!string.IsNullOrEmpty(searchObj.CR_DCSN_ID))
credit_verdict = searchObj.CR_DCSN_ID.Trim();
if (!string.IsNullOrEmpty(searchObj.SBSA_CUST_I))
sbsa_cust_id = searchObj.SBSA_CUST_I.Trim();
if (!string.IsNullOrEmpty(searchObj.USER_ID_APP_CRTD))
app_creator_id = searchObj.USER_ID_APP_CRTD.Trim();
using (var context = new VASTEntities())
{
var query = from p in context.APLCN_TRCKR
where
p.CUST_NAME_X.Contains(cust_name_x) &&
p.CUST_SURNM_X.Contains(surname_x) &&
p.QUEUE_ID.Contains(queue_id) &&
p.BPID.Contains(bp_id) &&
p.CURR_OWNR_USER_ID.Contains(user_id) &&
p.APLCN_TRCKR_ID.Contains(aplcn_trckr_id) &&
p.APLCN_STTS_ID.Contains(aplcn_stts_id) &&
p.CUST_ID.Contains(cust_id) &&
p.PRCES_TYPE_ID.Contains(process_type) &&
p.CELL_ID.Contains(cell_id) &&
SqlFunctions.StringConvert((double)p.CR_REGION_ID).Contains(cr_region) &&
p.ORIGN_ID.Contains(Origin) &&
SqlFunctions.StringConvert((double)p.RGION_ID).Contains(region) &&
p.ORGTN_CHANL_ID.Contains(channel) &&
p.CR_DCSN_ID.Contains(credit_verdict) &&
p.SBSA_CUST_I.Contains(sbsa_cust_id)
select p;
query.ToList();
if (query.Count() == 0)
{
throw new Exception("No Applications Found.");
}
foreach (var a in query)
{
searchAppsObj.Add(Translator.TranslateReqObjToBO.TranslateDTOToSearchApp(a));
}
context.Connection.Close();
return searchAppsObj;
}
You can just create a collection of lambda expression like below:
var filters = new List<Expression<Func<Application, bool>>>();
if (!string.IsNullOrWhitespace(searchObj.CUST_NAME_X))
filters.Add(application => application .CUST_NAME_X.Contains(searchObj.CUST_NAME_X.Trim());
if (!string.IsNullOrEmpty(searchObj.SURNM_X))
filters.Add(application => application .CUST_SURNM_X.Contains(searchObj.SURNM_X.Trim());
// And so on for all criteria
After that you can do a loop on filters like below:
using (var context = new VASTEntities())
{
var query = context.APLCN_TRCKR;
foreach(var filter in filters)
{
query = query.Where(filter);
}
var result = query.ToList();
if (result.Count() == 0)
{
throw new Exception("No Applications Found.");
}
foreach (var a in result)
{
searchAppsObj.Add(Translator.TranslateReqObjToBO.TranslateDTOToSearchApp(a));
}
context.Connection.Close();
return searchAppsObj;
}
change
var query = from p in context.APLCN_TRCKR select p;
to
var query = context.APLCN_TRCKR.AsQueryable();
And when the filtering work is done:
await query.ToListAsync() // this one goes to the database
Also have a look at this: Linq query filtering
In Addition: don't call context.Connection.Close(); as this is going to be executed anyway because using behaves like try { ... } finally { // dispose work }

Salesforce Trigger Test Class

below is my Apex Trigger. I am a beginner and trying to write its test class but continuously getting error "System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Error: You can't select products until you've chosen a price book for this opportunity on the products related list.: []".
trigger TrgrOptyHighestCustmorePrice on Opportunity (before insert, before update)
{
public Id oid;
public String bidType;
public String BUCode;
for(Opportunity o : trigger.new)
{
oid = o.Id;
bidType = o.BidType__c;
BUCode = o.Business_Line_BU__c;
}
List<OpportunityLineItem> oliList = new list<OpportunityLineItem>([SELECT id, Customer_Price__c, ReCat_Product_Line__c
FROM OpportunityLineItem
WHERE OpportunityId =: oid ORDER BY
Customer_Price__c DESC LIMIT 1]);
for(OpportunityLineItem oli : oliList)
{
if(bidType == 'Competitive' && oli.ReCat_Product_Line__c == 'DMS')
{
BUCode = 'BL.619';
}
if(bidType == 'Competitive' && (oli.ReCat_Product_Line__c == 'EMS' || oli.ReCat_Product_Line__c == 'GMS'))
{
BUCode = 'BL.620';
}
if(bidType == 'Competitive' && oli.ReCat_Product_Line__c == 'MMS')
{
BUCode = 'BL.622';
}
if(bidType == 'Sole Sourced' && oli.ReCat_Product_Line__c == 'DMS')
{
BUCode = 'BL.624';
}
if(bidType == 'Sole Sourced' && (oli.ReCat_Product_Line__c == 'EMS' || oli.ReCat_Product_Line__c == 'GMS'))
{
BUCode = 'BL.621';
}
if(bidType == 'Sole Sourced' && oli.ReCat_Product_Line__c == 'MMS')
{
BUCode = 'BL.623';
}
}
for(Opportunity opt : trigger.new)
{
opt.Business_Line_BU__c = BUCode;
}
}
Test Class
#isTest(seeAllData=true)
public class Test_TrgrOptyHighestCustmorePrice {
private static testmethod void TrgrOptyHighestCustmorePriceTest(){
Test.startTest();
//Insert a test product.
Product2 p1 = new Product2(Name='Product Monthly 1111', isActive=true, CurrencyIsoCode='USD', ReCat_Product_Line__c = 'DMS');
insert p1;
// Get standard price book ID.
Id pricebookId = Test.getStandardPricebookId();
// Insert a price book entry for the standard price book.
PricebookEntry standardPrice = new PricebookEntry(
Pricebook2Id = pricebookId, Product2Id = p1.Id,
UnitPrice = 10000, IsActive = true);
insert standardPrice;
Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
insert customPB;
PricebookEntry customPrice = new PricebookEntry(
Pricebook2Id = customPB.Id, Product2Id = p1.Id,
UnitPrice = 12000, IsActive = true);
insert customPrice;
// Insert Opportunity
Opportunity opt = new Opportunity(Name='Test',StageName='Prospect',
CloseDate=date.today(),BidType__c = 'Competitive',
Business_Line_BU__c = 'BL.619',
PriceBook2 = customPB);
insert opt;
OpportunityLineItem optLI = new OpportunityLineItem(OpportunityId = opt.id, Product2Id = p1.Id);
insert optLI;
update opt;
Test.stopTest();
}
}
I am unable to understand how can I test my simple trigger.
Its because u do not fill all required fields for the Opportunity Line Item. See: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_opportunitylineitem.htm for required fields.
This as an example will work:
OpportunityLineItem optLI = new OpportunityLineItem(OpportunityId = opt.id, Product2Id = p1.Id, TotalPrice = 100, PricebookEntryId=customPrice.Id, Quantity =3);
First Insert the opportunity.
Then update the opportunity with the pricebookid.
// Insert Opportunity
Opportunity opt = new Opportunity(Name='Test',StageName='Prospect',
CloseDate=date.today(),BidType__c = 'Competitive',
Business_Line_BU__c = 'BL.619'
);
insert opt;
opt.PriceBook2 = customPB;
update opt;

Single database call pulling data from multiple tables in EF Core

The following code currently opens a connection three times to my database, to pull out each object.
Is there a better way to craft the query so the database is only hit once and pulls back all the objects I'm looking for?
var metadataResult = new MetadataViewModel
{
Milestones = goalsContext.Milestones.Select(m => new MilestoneViewModel
{
Id = m.Id,
Name = m.Name,
Year = m.Year,
Date = m.Date
}),
Aggregates = goalsContext.Aggregates.Select(a => new AggregateViewModel
{
Id = a.Id,
Name = a.Name
}),
Metrics = goalsContext.Metrics.Select(m => new MetricViewModel
{
Id = m.Id,
Name = m.Name,
Description = m.Description
})
};
If your view models are a fairly similar shape then you should be able to use Union to get everything in one query and then transform the rows into appropriate ViewModel instances afterwards. Something like the following -
var combinedResults =
context.Products.Select(p => new
{
Type = "Product",
ID = p.ProductID,
Name = p.ProductName,
SupplierName = p.Supplier.CompanyName
})
.Union(
context.Categories.Select(c => new
{
Type = "Category",
ID = c.CategoryID,
Name = c.CategoryName,
SupplierName = (string)null
})
)
.ToList();
var viewModel = new ViewModel
{
Products = combinedResults
.Where(x => x.Type == "Product")
.Select(x => new ProductViewModel
{
ID = x.ID,
Name = x.Name,
SupplierName = x.SupplierName
}),
Categories = combinedResults
.Where(x => x.Type == "Category")
.Select(x => new CategoryViewModel
{
ID = x.ID,
Name = x.Name
})
};

Entity Framework - how to select properties from two database class to another class

I Made a new notMapped class "BuyingHistory", that have some property (not all) of two database tables
how to fill this class with entity? I made the conditions, but how do I select the properties to a list? (I know how to do it for one property but not for a list)
IQueryable<BuyingHistory> _buyingList =
_db.Orders
.Join(_db.EventPages
,o => o.EventID
,e => e.ID
,(o, e) => new { orders = o, events = e })
.Where(o => o.orders.UserID == LS.CurrentUser.ID)
.Select( // I don't know how to continue
it's work in this way bellow, but how can I do it in one command like the example above
var _List =
_db.Orders
.Join(_db.EventPages
, o => o.EventID
, e => e.ID
, (o, e) => new { orders = o, events = e })
.Where(o => o.orders.UserID == LS.CurrentUser.ID).ToList();
List<BuyingHistory> _buyingList = new List<BuyingHistory>();
foreach (var item in _List)
{
_buyingList.Add(new BuyingHistory()
{
CreatedDate = item.orders.CreatedDate,
EventName = item.events.Title,
NumberOfTickets = item.orders.TicketNumber,
OrderID = item.orders.ID,
Status = item.orders.Status.ToString(),
Total = item.orders.TicketNumber
});
}
I'd use query syntax to begin with, and then do the query like so:
from ord in _db.Orders
join evt in _db.EventPages on ord.EventID equals evt.ID
where ord.UserID == LS.CurrentUser.ID
select new BuyingHistory
{
CreatedDate = ord.CreatedDate,
EventName = evt.Title,
NumberOfTickets = ord.TicketNumber,
OrderID = ord.ID,
Status = ord.Status.ToString(),
Total = ord.TicketNumber
})
If you have EF version 6 the ToString() won't throw exceptions. If not, you have to change the type of BuyingHistory.Status into the type coming from the database.